`bytes` and `bytearray`
bytes is an immutable sequence of integers in 0..255. bytearray is the mutable counterpart. Both represent raw binary data, not Unicode text.
Detailed Explanation
Text is str. Binary is bytes. A PNG, a length-prefixed protocol frame, and the output of hashlib are bytes. You create them with a literal (b"PNG"), bytes(range(4)), bytes.fromhex("00ff"), or str.encode.
Indexing returns an int. Slicing returns bytes (or bytearray). That split is the usual first bug: data[0] == b"P" is False because 80 != b"P". Compare to 80 or to data[0:1].
bytes is hashable and can be a dict key. It supports the sequence operations: in (for an int or a short bytes), concatenation, repetition, find, split, join (of other bytes). Methods that look like str methods (upper, replace, startswith) operate on ASCII bytes and do not decode Unicode.
bytearray has the same payload and is mutable. You can assign an index, slice-assign, append, extend, and +=. Use it when you are assembling a buffer incrementally. Call bytes(buf) when you need to freeze the result for hashing or for an API that wants bytes.
memoryview can sit on top of either and expose slices without copying. struct packs and unpacks numbers into bytes. array.array is a typed mutable sequence that can also export the buffer protocol. For large numeric data, NumPy is the usual next step.
Never decode arbitrary bytes as UTF-8 "to print them" unless you know they are text. Use data.hex(), repr(data), or data[:32] in logs. A failed decode is better than a string that looks almost right.
Code Examples
header = b"\x89PNG\r\n\x1a\n"
print(header[0], header[0:1]) # 137 b'\x89'
print(header.startswith(b"\x89PNG")) # True
print(header.hex()) # 89504e470d0a1a0abuf = bytearray()
buf.extend(b"HDR")
buf.append(0x00)
buf[0] = ord("h")
print(bytes(buf)) # b'hDR\x00'
# fromhex / hex are the usual debug pair.
print(bytes.fromhex("00 0a ff")) # b'\x00\n\xff'# bytes are hashable; bytearray is not.
cache = {b"png": "image"}
print(cache[b"png"]) # image
# cache[bytearray(b"png")] # TypeError: unhashable type: 'bytearray'Common Gotchas
`b"abc"[0]` is `97`
compare slices or integers, not a `bytes` literal to an index.
Concatenating `bytes` and `str`
`TypeError`. Encode or decode first.
`bytearray` is unhashable
freeze with `bytes(buf)` before using it as a key.
Text methods on `bytes` are ASCII-oriented
`b"é".upper()` is not a Unicode uppercasing. Decode if the data is text.