5.7 Binary Data Types
Python's binary types — bytes, bytearray, and memoryview — for working with raw, non-text data like files, sockets, and cryptographic operations.
These represent raw bytes rather than text — essential whenever Python touches files, network sockets, or any non-text data.
bytes
An immutable sequence of raw 8-bit values (0–255 each). What you get from reading a file in binary mode, or encoding a str (see 9.7 Common String Methods).
>>> b = bytes([104, 105])
>>> b
b'hi'
bytearray
The mutable counterpart to bytes — lets you modify raw byte data in place, useful when building up a binary buffer incrementally.
>>> ba = bytearray(b"hi")
>>> ba[0] = 72
>>> ba
bytearray(b'Hi')
memoryview
What Is It?
A view onto another object’s underlying memory buffer WITHOUT copying it.
Why Is It Used?
Processing large binary data (e.g. a big file read into bytes) efficiently, avoiding the cost of duplicating it in memory.
>>> mv = memoryview(b"hello")
>>> mv[0]
104
>>> bytes(mv)
b'hello'
Binary Data Use Cases
- Reading/writing files in binary mode (images, archives, executables)
- Network protocol implementation (raw socket data)
- Cryptographic operations (hashing, encryption work on bytes)
Quick Interview Answer
“
bytesis an immutable sequence of raw 8-bit values — what you get reading a file in binary mode or encoding a string.bytearrayis its mutable counterpart, for building up a binary buffer in place.memoryviewgives a zero-copy view onto another object’s memory buffer, which matters for processing large binary data efficiently.”
Common Mistakes
- Trying to mutate a
bytesobject directly — it’s immutable; usebytearraywhen in-place modification is needed. - Mixing up
strandbytes(e.g. writing astrto a file opened in binary mode) — Python raises aTypeErrorrather than silently converting. - Copying a large
bytesobject unnecessarily instead of usingmemoryviewto operate on it in place.
Add More Questions to This Guide
Know a question that should be here? Share it and help the community!
Open Google Form