Python Memoryview Slicing: Views, Syntax, and Pitfalls
Learn how Python memoryview slicing works: view creation, index rules, performance impact, and common pitfalls when slicing binary buffers.

When you slice a Python memoryview, you get a new memoryview that references the same underlying buffer. That behavior makes slicing a cheap way to work with a subset of binary data. It also means you need to understand exactly how indices are resolved and when a slice keeps the original buffer alive.
How memoryview slicing works
A memoryview is an object that exposes a buffer's data without copying it. Slicing a memoryview returns a new memoryview that references the same buffer, but with a restricted range. The slice operation uses the same syntax as list or tuple slicing: mv[start:stop:step]. The result is another memoryview, not a list or bytes.
data = bytearray(b'abcdefgh')
mv = memoryview(data)
sub = mv[2:6]
print(sub.tobytes()) # b'cdef'Here sub is a memoryview that points to bytes at positions 2 through 5 of the original buffer. No copy of the data is made. The data object is still the owner of the buffer, and sub is a separate view.
Slicing syntax and index rules
The slice parameters follow the same rules as for other sequence types in Python. start, stop, and step are all optional. Negative indices are counted from the end of the view. A step value other than 1 creates a view with non-contiguous elements, which has important consequences for how you read and write data.
mv = memoryview(b'0123456789')
print(mv[::2].tobytes()) # b'02468'
print(mv[-3:].tobytes()) # b'789'
print(mv[8:2:-2].tobytes()) # b'864'When you use a negative step, the logical order of the view is reversed. Iterating over the view yields elements from the original buffer in reverse order, but the underlying data is not physically reordered.
Slicing returns a view, not a copy
The most important distinction is that slicing a memoryview does not copy the data. It creates a new view object that shares the same buffer. This has two immediate consequences.
First, writes through the slice modify the original buffer. If you change sub[0], the corresponding byte in data changes. Second, the slice keeps the original buffer alive as long as the slice exists. If you hold a slice of a large buffer, the whole buffer remains in memory, even if you only need a small portion.
data = bytearray(b'abcdef')
mv = memoryview(data)
sub = mv[1:3]
sub[0] = ord('X')
print(data) # bytearray(b'aXcdef')This behavior is useful when you want to edit a region in place, but it can be a source of memory pressure if you store many slices of a large buffer.
Multi-dimensional memoryviews and slicing
Memoryviews can be multi-dimensional when the underlying object exposes a multi-dimensional buffer, such as a NumPy array. For a multi-dimensional view, use a tuple of indices or slices, one entry per dimension. For example, mv[1, :] selects the second row of a shape (2, 3) view. A single index such as mv[1] is not enough for a multi-dimensional view; you need a tuple like mv[1, :].
For flat binary data, you usually do not need multi-dimensional slicing. For structured binary records, use struct or array with a defined format, then slice the resulting memoryview as a one-dimensional sequence.
Performance and memory behavior of slicing
The main performance advantage of memoryview slicing is that it avoids copying. Creating a slice is an O(1) operation because it only stores the buffer pointer, offset, and length. This makes it attractive for parsing large binary files or network packets where you want to isolate a header or a field without copying the entire payload.
However, step slices have a performance cost. When you use a step other than 1, the view is not C-contiguous. Operations that iterate over the view, such as tobytes(), may need to handle the stride and can be slower than operating on a contiguous slice. If you need a contiguous copy for a downstream API, call tobytes() or bytes(mv) to get one. A non-contiguous view cannot be made contiguous with cast(); cast() requires a C-contiguous source.
Memory usage is also affected by the fact that a slice keeps the original buffer alive. If you create a slice of a large memory-mapped file and then discard the original memoryview, the slice still holds a reference to the buffer, so the file remains mapped. This is usually fine, but it can lead to unexpected memory consumption if you keep many small slices of a large buffer.
Common slicing mistakes and how to avoid them
One common mistake is assuming that slicing a memoryview creates an independent copy. As shown earlier, writes through the slice affect the original buffer. If you need a copy, use tobytes() or bytes(mv) to create a new bytes object.
Another mistake is trying to cast() a non-contiguous memoryview. The cast() method requires a C-contiguous view; a view returned by a step slice is not contiguous and will raise TypeError if you cast it.
Also, be careful with negative indices and steps. The semantics are the same as for lists: slicing an out-of-range range returns an empty view rather than raising, while an out-of-range element access such as mv[10] raises IndexError.
mv = memoryview(b'abc')
print(mv[10:20].tobytes()) # b''
# mv[10] would raise IndexErrorFinally, don't assume that a view remains valid if the underlying object is resized. In CPython, creating a memoryview exports the buffer, so a bytearray refuses to resize while a view exists and raises BufferError. Other buffer providers may behave differently, so the safe pattern is to create memoryviews around data you intend to keep stable and release them before resizing the owner if the owner allows it.
Using memoryview slicing for binary data parsing
A practical use of memoryview slicing is parsing binary protocols without copying the entire payload. Suppose you receive a network packet as a bytes object. You can create a memoryview and slice out the header and body fields.
packet = b'\x01\x02\x03\x04payload'
mv = memoryview(packet)
header = mv[:4]
body = mv[4:]
# Interpret header as two 16-bit integers
import struct
a, b = struct.unpack('!HH', header)Because header and body are views, no copy of the packet is made. If you need to modify the payload before sending it onward, you can create a bytearray and use the same slicing technique to edit specific fields in place.
This pattern is especially useful when you are processing many packets in a loop. Creating a memoryview for each packet is cheap, and slicing avoids the allocation cost of bytes slicing, which always creates a new bytes object.
For more complex binary formats, you can combine memoryview slicing with struct.iter_unpack or memoryview.cast to interpret the data as a sequence of fixed-size records. The key is to keep the view contiguous when you need to cast it, and to be aware that a slice is not a copy.
Try matching browser tools
All toolsSmall utilities that fit Python work — they run entirely in this browser tab, so nothing you paste leaves your device.
Related Python guides
All Python guidesPython iter(): How the Built-in Function Works
Explains Python's iter() built-in: how it creates iterators, the two-argument sentinel form, custom iterator classes, and common edge cases.
Python Pika: Queues, Exchanges, Routing Keys, and Acknowledgements
Learn how to use Python's Pika client with RabbitMQ: declare queues and exchanges, publish with routing keys, consume messages, and handle acknowledgements reliably.
Python Kafka: kafka-python vs Confluent Client
python kafka python vs confluent kafka: Compare kafka-python and Confluent Kafka Python clients: API differences, performance, feature coverage, and when to choose eac...
Python Kafka Offsets, Partitions, and Manual Commits
Learn how Kafka offsets and partitions work and how to manually commit offsets in Python consumers with kafka-python and confluent-kafka. Covers sync vs async commits, rebalances, and seeking.
More in Python
All Python guidesThe guides filed next to this one in Python, in library order.