Skip to main content

memoryview()

The memoryview() function in Python returns a memory view object that exposes the internal data of an object in a memory-efficient way. It allows for accessing and manipulating the memory contents of objects like bytes, bytearray, and array.array without copying the data.

Parameter Values

Parameter Description
obj

The obj parameter is the object whose internal data is to be exposed. It can be an object that implements the buffer protocol, such as bytes, bytearray, or any object exposing the buffer interface.

flags

The flags parameter is optional. It can be a combination of one or more of the following strings: 'c_contiguous', 'f_contiguous', 'fortran', 'aligned', 'writeable', 'native'. These flags can be used to control how the data is exposed and interpreted by the memoryview object.

Return Values

The memoryview object supports numpy.ndarray, bytes, bytearray, and array.array.

How to Use memoryview() in Python

Example 1:

The memoryview() function in Python returns a memory view object of the given argument.

data = bytearray(b'Hello World')
view = memoryview(data)
print(view[2:9].tobytes())
Example 2:

The memory view object allows access to the internal data of an object without making a copy.

word = 'Python'
view = memoryview(word.encode())
print(list(view)[1:4])
Example 3:

Memoryview objects can be used with mutable objects like bytearray.

nums = bytearray([1, 2, 3, 4, 5])
view = memoryview(nums)
view[2] = 9
print(nums)