Python memoryview()

Python memoryview() builtin function used to get a Memory View object created from the given bytes-like object. Memory View object allows Python code to access the internal data of an object that supports the butter protocol.

In this tutorial, we will learn about the syntax of Python memoryview() function, and learn how to use this function with the help of examples.

Syntax

The syntax of memoryview() function is

memoryview(object)

where

ParameterRequired/OptionalDescription
objectRequiredA bytes-like object. For example b'Hello World'.

Returns

The function returns Memory View object.

ADVERTISEMENT

Example

In this example, we take a string as bytes object, and pass it as argument to memoryview() function. Using the memory object returned by memoryview() function ,we may access the data.

Python Program

x = memoryview(b'abcdefgh')
print(x[1])
print(x[5])
print(x[-2])
Try Online

Output

98
102
103

x[1] is the byte corresponding to character b which is 98. Same is the the case for x[5] and x[-2]. x[-2] is the second element from the other end of the object in memory.

Conclusion

In this Python Tutorial, we have learnt the syntax of Python memoryview() builtin function, and also learned how to use this function, with the help of Python example programs.