memoryview() Built-in Function

Python – memoryview()

Python memoryview() built-in function is used to get the memory view object that allows you to view the contents of a bytes-like object as a sequence of machine values.

memoryview() built-in function can be used for efficient data manipulation, sharing memory between objects, interacting with C code, etc.

In this tutorial, you will learn the syntax and usage of memoryview() built-in function, and cover some examples.

Syntax

The syntax of memoryview() function is

memoryview(object)

where

Parameter Description
object A bytes-like object. e.g., bytes, bytearray, or another memory view object.

Examples

1. Get memory view of bytes object

In the following program, we take a bytes object, and get a memoryview object for this bytes object.

Python Program

data = bytearray(b'hello world')

# Get memory view of data
mv = memoryview(data)
print(mv)
Run Code

Output

<memory at 0x104725d80>

2. Slice memoryview

memoryview supports slicing. In the following program, we slice the memoryview object, and print it to standard output.

Python Program

data = bytearray(b'hello world')

# Get memory view of data
mv = memoryview(data)

# Slice memoryview
mvslice = mv[2:8]
print(bytes(mvslice))
Run Code

Output

b'llo wo'

Uses of memoryview()

memoryview() built-in function can be used for the following purposes.

Summary

In this Built-in Functions tutorial, we learned the syntax of the memoryview() built-in function, and how to use this function to create a memoryview for a bytes-like object.

Related Tutorials

Privacy Policy Terms of Use

SitemapContact Us