8.7 Binary Type Conversion
Converting between text and raw binary data with bytes(), bytearray(), and memoryview() — the conversion rules for each, not just what they are.
bytes, bytearray, and memoryview themselves are covered in 5.7 Binary Data Types — this section focuses on the conversion rules for constructing each from other types, essential whenever Python touches files, sockets, or non-text data.
bytes()
Converts a list of integers (0–255), or a str with an explicit encoding, into an immutable bytes object.
>>> bytes([65, 66, 67])
b'ABC'
>>> bytes("hi", "utf-8")
b'hi'
bytearray()
Same conversion rules as bytes(), but produces a mutable result that can be modified in place afterward.
>>> bytearray("hi", "utf-8")
bytearray(b'hi')
memoryview()
Wraps an existing bytes/bytearray object as a zero-copy view — converting it back to a list of integers shows the underlying byte values without duplicating the buffer.
>>> list(memoryview(b"hi"))
[104, 105]
Quick Interview Answer
“
bytes()builds an immutable byte sequence either from a list of integers in the 0–255 range, or from astrgiven an explicit encoding — Python never guesses an encoding, it must be stated.bytearray()follows the same construction rules but produces a mutable result.memoryview()is different in kind: it doesn’t copy data at all, just wraps an existingbytes/bytearraybuffer, which matters for processing large binary data without duplicating it in memory.”
Common Mistakes
- Calling
bytes("hi")without an encoding argument — unlike some conversions,strtobytesrequires an explicit encoding; Python won’t assume one. - Expecting
memoryview()to copy data like the other conversions do — it’s a zero-copy view onto the original buffer, not a new independent object.
Add More Questions to This Guide
Know a question that should be here? Share it and help the community!
Open Google Form