memoryview() in Python (original) (raw)

Last Updated : 12 Jan, 2026

memoryview() provides direct access to an object’s memory (like bytes, bytearray, or array) without copying it, making operations on large datasets faster and more efficient.

**Example:

Python `

Creating a memory view of a bytearray

data = bytearray("Hello", "utf-8")
mv = memoryview(data)

print(mv[0])
mv[1] = 105
print(data)

`

Output

72 bytearray(b'Hillo')

**Explanation:

Syntax

memoryview(object)

Different methods of Using memoryview()

1. Accessing bytes using indexing

You can use indexing or slicing to access specific bytes in a memory view.

Python `

data = b'Python' mv = memoryview(data)

print(mv[0])
print(mv[1:4].tobytes())

`

**Explanation:

2. Modifying data using bytearray

If the underlying object is mutable (like bytearray), you can modify it directly through the memory view.

Python `

arr = bytearray(b'abcde')
mv = memoryview(arr)

Modifying a byte using indexing

mv[0] = 65
print(arr)

`

Output

bytearray(b'Abcde')

**Explanation:

3. Converting memory view to bytes

The .tobytes() method converts the memory view into an immutable bytes object, which is a copy of the data.

**Example:

Python `

arr = bytearray(b'12345')
mv=memoryview(arr)

res = mv.tobytes()
print(res)
print(type(res))

`

Output

b'12345' <class 'bytes'>

**Explanation:

4. Reinterpreting Data Using .cast()

The .cast() method lets you interpret the memory as a different data type without changing the actual data. This is useful when working with binary data or arrays.

Python `

import array

arr = array.array('i', [1, 2, 3, 4])
mv=memoryview(arr)

mv_cast = mv.cast('B')
print(mv_cast.tolist())

`

Output

[1, 0, 0, 0, 2, 0, 0, 0, 3, 0, 0, 0, 4, 0, 0, 0]

**Explanation: