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

Create a free account to save this page, take notes and track your progress. Sign in

Syntax

memoryview(object)

Parameters

ParameterDescription
object An object that supports the buffer protocol, such as bytes or bytearray.

Return value

A memoryview object.

Examples

Edit a slice in placeTry it yourself
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')
Slice without copyingTry it yourself
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

VersionChange
Python 3.0Added

Was this page helpful?