bytes()

The immutable byte-sequence type — the type on the other side of str.encode.

Built-in function / typePython 3.0+Live demo
Common call
bytes(text, "utf-8")
Returns
a bytes object — immutable
Replaces
raw byte-array construction; bytearray is the mutable sibling
Watch out
bytes(5) does NOT mean "the digit 5" — it is FIVE zero bytes
bytes(sourcesourceThe initial data. int: number of zero bytes. Iterable of ints: those bytes. String: requires encoding.type: int | iterable | str · default: ""=..., encodingencodingWhen source is a string, the encoding to use. Same values as str.encode: "utf-8" (recommended), "ascii", "latin-1", ...type: str · default: null=..., errorserrorsError handler when encoding a string. Same values as str.encode.type: str · default: "strict"=...)
bytes

Demo

Live evaluation
Try:
Inputs
sourcestrtext or comma-separated ints
encodingstrutf-8 / ascii / latin-1 (for str)
Output
bytes('hello', 'utf-8')
'b\'hello\''

bytes() has THREE call shapes. Passing a STRING plus an encoding calls str.encode — the most common use. Passing an INT gives that many zero bytes: `bytes(5)` = five zero bytes (NOT the digit 5). Passing a comma-separated LIST of ints creates bytes from those values (each 0..255). The demo displays results in Python's b'...' literal form.

Parameters

NameTypeRequiredDescription
sourceint | iterable | strno ("")The initial data. int: number of zero bytes. Iterable of ints: those bytes. String: requires encoding.
encodingstrnoWhen source is a string, the encoding to use. Same values as str.encode: "utf-8" (recommended), "ascii", "latin-1", ...
errorsstrno ("strict")Error handler when encoding a string. Same values as str.encode.

Return value

bytesAn immutable sequence of bytes (integers 0..255). Three call shapes: `bytes(int)` → n zero bytes; `bytes(iterable_of_ints)` → those bytes; `bytes(str, encoding)` → same as str.encode(encoding).

Common patterns

Encode a string
The most common use — same as str.encode.
data = bytes(text, "utf-8")
# equivalent to: text.encode("utf-8")
Pre-allocate a buffer
Passing an int gives that many zero bytes.
buffer = bytes(1024)   # 1024 zero bytes
From explicit byte values
Build a bytes object from a list of ints (0..255).
magic = bytes([0x89, 0x50, 0x4e, 0x47])   # PNG header
From a bytes literal
Direct literal — no constructor needed for small constants.
header = b"HTTP/1.1 200 OK\r\n"

Examples

1. From string, utf-8
bytes("hello", "utf-8")
Returns
b'hello'
2. From string, accents
bytes("café", "utf-8")
Returns
b'caf\xc3\xa9'
3. From list of ints
bytes([65, 66, 67])
Returns
b'ABC'
4. Int gives zero bytes
bytes(5)
Returns
b'\x00\x00\x00\x00\x00'
5. Zero-size
bytes(0)
Returns
b''
6. From bytes
bytes(b"hi")
Returns
b'hi' # copy
7. Range of ints
bytes(range(3))
Returns
b'\x00\x01\x02'

Pitfalls

1. bytes(5) is NOT b"5" — it is FIVE zero bytes
The single most common bytes() surprise. Passing an int means "that many zero bytes", not "the digit as a byte". If you want to write "5" as a byte, wrap it in a list or use a bytes literal.
Assumed digit
bytes(5)
b'\x00\x00\x00\x00\x00'
For the digit
bytes([5])   # b'\x05'
b"5"           # b'5'
literal vs digit vs char
2. String without encoding raises TypeError
Unlike str(x), which coerces anything to a string, bytes(str) requires an encoding. This is deliberate — no default encoding assumption.
Missing encoding
bytes("hello")
TypeError: string argument without an encoding
Add encoding
bytes("hello", "utf-8")
b'hello'
3. Iterable elements must be 0..255
Every value in the iterable must fit in a byte. Larger or negative ints raise ValueError.
Out of range
bytes([256, 0])
ValueError: bytes must be in range(0, 256)
Mask to byte
bytes([x & 0xff for x in values])
clamped
4. bytes is IMMUTABLE — bytearray is the mutable sibling
bytes is a sequence of bytes; you can index and slice but not modify. For an in-place mutable buffer, use bytearray.
Cannot assign
b = bytes([1, 2, 3])
b[0] = 9
TypeError: 'bytes' object does not support item assignment
Use bytearray
b = bytearray([1, 2, 3])
b[0] = 9
bytearray(b'\t\x02\x03')

When to use

Use it
  • Preparing text for byte-oriented output (network, binary file)
  • Constructing binary payloads from a list of byte values
  • Pre-allocating a fixed-size zero buffer
  • Explicit conversion when the encoding matters
Reach for something else
  • Direct constant literal → use b"..." literal instead of calling bytes()
  • You need to mutate — use bytearray
  • You have a str you want to inspect — work with str, only convert at the boundary
  • You want a specific integer as a byte — use bytes([n]), not bytes(n)

Notes

Complexity
O(n) in the length of the source
Return
A new bytes object — immutable
CPython impl
Objects/bytesobject.c :: bytes_new
Memory
Allocates one bytes object; the internal buffer is compact
Thread-safe
Yes — bytes objects are immutable

FAQ

bytes is a sequence of bytes (integers 0..255). str is a sequence of Unicode codepoints. bytes is for binary data — files, network, protocols. str is for text. Convert between them with str.encode / bytes.decode, always with an explicit encoding.

History

3.0
bytes became a distinct type separate from str (Python 2 str was byte-like).
3.5
bytes literal % formatting added.