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 |
flags | The |
Return Values
The memoryview
object supports numpy.ndarray
, bytes
, bytearray
, and array.array
.
How to Use memoryview()
in Python
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())
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])
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)