Distinguish bytes and bytearray
Core idea
Binary data is a sequence of integers from 0 to 255. bytes is immutable; bytearray allows in-place changes. Convert explicitly when a mutable working buffer or an immutable snapshot is needed.
raw = bytes([65, 0, 255])print(raw[0], raw.hex())print(raw[:1])Indexing gives an integer; slicing gives bytes. Hexadecimal displays every byte as two digits.
Patch a working copy
raw = b"ABC"work = bytearray(raw)work[1] = 90work.append(33)print(raw, bytes(work))The original stays unchanged; the mutable copy is converted back to bytes.
Common mistake
Assigning to a bytes index raises TypeError. A byte value outside 0–255 is invalid; bytes(3) creates three zero bytes, not a byte with value 3.
Practice
Patch the first byte of a list of byte values to 1 if it is nonempty, and return its hex string.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Binary sequence basics
Check your understanding of bytes and bytearray.
What is printed?
print(b"\xff"[0])What is printed?
print(bytes(2).hex())Which type allows index assignment?
Which value is a valid single byte?