Python 3 reference · Built-in Functions
Python memoryview() Function
Create a view of an object's binary data (bytes, bytearray, arrays) that slices and edits it without copying.
Python 3 Since 3.0
Syntax
memoryview(object)
Parameters
| Parameter | Description |
|---|---|
object |
An object that supports the buffer protocol, such as bytes or bytearray. |
Return value
A memoryview object.
Examples
data = bytearray(b"hello world")
view = memoryview(data)
view[0:5] = b"HELLO" # edits data, no copy made
print(data)
Output
bytearray(b'HELLO world')
buf = memoryview(b"abcdef")
part = buf[2:4]
print(part.tobytes(), len(part), part[0])
Output
b'cd' 2 99
When to use it
memoryview matters for large binary data (images, network buffers): slicing bytes copies, slicing a
memoryview doesn't.
Version history
| Version | Change |
|---|---|
| Python 3.0 | Added |
Related
bytes()· Create an immutable sequence of bytes: raw binary data such as file contents, network messages or encoded text.bytearray()· Create a mutable sequence of bytes (integers 0–255). Like bytes, but you can change, append and remove bytes in place.