⬅ Previous Topic
Python max() Function – Find the Largest ValueNext Topic ⮕
Python min() Function – Find the Smallest Value⬅ Previous Topic
Python max() Function – Find the Largest ValueNext Topic ⮕
Python min() Function – Find the Smallest Valuememoryview()
FunctionThe memoryview() function in Python provides a way to access the memory of a binary object (like bytes
or bytearray
) without copying the actual data. It's very useful for working with large data buffers efficiently.
memoryview(obj)
obj
– A binary object that supports the buffer protocol, like bytes
, bytearray
, or array.array
.memoryview()
with bytearray
data = bytearray("hello", "utf-8")
mv = memoryview(data)
print(mv[0]) # Output: 104 (ASCII of 'h')
mv[0] = 72 # Change 'h' to 'H'
print(data) # Output: bytearray(b'Hello')
104
bytearray(b'Hello')
memoryview()
?numbers = bytearray([10, 20, 30, 40, 50])
mv = memoryview(numbers)
slice_mv = mv[1:4]
print(list(slice_mv))
[20, 30, 40]
mv = memoryview(b"data")
print(bytes(mv))
b'data'
memoryview()
on non-buffer objects like strings → will raise TypeError
memoryview
of bytes
(which is immutable)In performance-sensitive applications (like image processing, network packets, or binary file handling), memoryview()
helps reduce memory overhead.
memoryview()
gives you access to the internal data of a binary object.Create a bytearray
from the word "data"
, convert it to a memoryview, change 'd' to 'D', and print the updated bytearray.
b = bytearray("data", "utf-8")
mv = memoryview(b)
mv[0] = ord("D")
print(b)
bytearray(b'Data')
⬅ Previous Topic
Python max() Function – Find the Largest ValueNext Topic ⮕
Python min() Function – Find the Smallest ValueYou can support this website with a contribution of your choice.
When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.