Guide Python Intermediate

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.

2 min read

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

bytes is an immutable sequence of raw 8-bit values — what you get reading a file in binary mode or encoding a string. bytearray is its mutable counterpart, for building up a binary buffer in place. memoryview gives a zero-copy view onto another object’s memory buffer, which matters for processing large binary data efficiently.”

Common Mistakes

  • Trying to mutate a bytes object directly — it’s immutable; use bytearray when in-place modification is needed.
  • Mixing up str and bytes (e.g. writing a str to a file opened in binary mode) — Python raises a TypeError rather than silently converting.
  • Copying a large bytes object unnecessarily instead of using memoryview to 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