Skip to content

memoryview()

The built-in memoryview() function provides a way to access the internal data of an object that supports the buffer protocol without copying it. It’s particularly useful for efficiently manipulating large datasets or interfacing with binary data:

Language: Python
>>> image = bytearray([0, 127, 255, 64])
>>> mv = memoryview(image)
>>> mv[0]
0

memoryview() Signature

Language: Python Syntax
memoryview(object)

Arguments

Argument Description
object An object supporting the buffer protocol, such as bytes, bytearray, or array.array.

Return Value

  • Returns a memoryview object, which allows for efficient access to the data without copying it.

memoryview() Examples

With a bytearray as an argument:

Language: Python
>>> data = bytearray(b"Hello")
>>> mv = memoryview(data)
>>> mv[1] = ord("a")
>>> bytes(mv)
b'Hallo'

With a bytes object as an argument:

Language: Python
>>> data = bytes(b"World")
>>> mv = memoryview(data)
>>> mv[0]  # ASCII for W
87

memoryview() Common Use Cases

The most common use cases for the memoryview() function include:

  • Accessing and manipulating slices of large datasets without copying them
  • Interfacing with C extensions or libraries that require buffer protocol support
  • Performing efficient operations on binary data, like image processing or data serialization

memoryview() Real-World Example

Suppose you have a bytearray representing pixel data of an image, and you want to invert the pixel values efficiently. You can use the memoryview() function:

Language: Python
>>> image = bytearray([0, 127, 255, 64, 128, 192, 32, 96, 160])
>>> mv = memoryview(image)

>>> for i in range(len(mv)):
...     mv[i] = 255 - mv[i]
...

>>> list(mv)
[255, 128, 0, 191, 127, 63, 223, 159, 95]

In this example, the memoryview object allows you to invert the pixel values directly, reflecting the changes on the original bytearray. This approach is memory-efficient and fast because it avoids unnecessary data copying.

Tutorial

Python Built-in Functions: A Complete Guide

Use Python's built-in functions for math, data types, iterables, and I/O to write shorter, more Pythonic code.

intermediate python

For additional information on related topics, take a look at the following resources:


By Leodanis Pozo Ramos • Updated Feb. 4, 2026 • Reviewed by Dan Bader