Python bytes() Function

Beginner
5 min read
Updated: Nov 2026
3 examples
Built-in type

Definition

In Python, bytes is an immutable sequence of small integers (0 to 255), used for binary data such as files, network packets, and encoded text. You can write a literal like b"Hi!" or call bytes().

bytes(n) makes n zero bytes, bytes([72, 105]) builds from ints, and bytes("Hi", "utf-8") encodes text. Indexing returns an int, slicing returns bytes, and .decode() turns the data back into a str. Use bytearray() when you need to change the data.

bytes is a built-in type (a class) that you call like a function: each call creates a new bytes object. Like every built-in, it lives in the builtins module and is always available without an import.

Syntax

Build bytes from a size, an iterable of ints, or text plus an encoding.

python
empty = bytes(3)                  # b'\x00\x00\x00'
data = bytes([72, 105])           # b'Hi'
encoded = bytes("Hi", "utf-8")    # b'Hi'
CallWhat it does
bytes(4)Four zero bytes.
bytes(range(65, 68))Returns b'ABC'.
"caf\u00e9".encode("utf-8")Returns b'caf\xc3\xa9'.
data.decode("utf-8")Turns bytes back into a str.

Printable ASCII bytes are shown as characters in the repr; all other values appear as \x.. escapes.

Library declarations
python
bytes(source=b"")
bytes(source, encoding, errors="strict")
# class bytes: an immutable built-in type

Parameters

ParameterDescription
sourceOptional. An int (size), an iterable of ints 0-255, a bytes-like object, or a str (requires encoding).
encodingRequired when source is a str. A codec such as "utf-8".
errorsOptional. What to do with characters the encoding cannot represent. Default "strict".

Return Value

Return ValueDescription
bytesA new immutable bytes object.

Python Examples

Example 1 — Five Ways to Create bytes

Build bytes from a size, a list of ints, a string with an encoding, a literal, and a range.

python
print(bytes(3))
print(bytes([72, 105, 33]))
print(bytes("Hi!", "utf-8"))
print(b"Hi!" == bytes([72, 105, 33]))
print(bytes(range(65, 70)))

How It Works

  1. Size gives zeros. bytes(3) creates three bytes with value 0, shown as \x00.
  2. From ints. 72, 105, and 33 are the ASCII codes for H, i, and !.
  3. From text. Encoding "Hi!" as UTF-8 produces exactly the same bytes, and they compare equal to the literal.
  4. From a range. 65 to 69 are the codes for A to E.

Example 2 — Encode Text, Index Bytes, and Decode

Encode a word with an accent, compare lengths, read single bytes, and decode back.

python
text = "caf\u00e9"
data = text.encode("utf-8")

print(data)
print(len(text), len(data))
print(data[0], data[-1])
print(data[:3])
print(ascii(data.decode("utf-8")))
print(list(data))

How It Works

  1. Two bytes for é. UTF-8 stores é as C3 A9, so 4 characters become 5 bytes.
  2. Index gives an int. data[0] is 99 (the letter c) and data[-1] is 169 (0xA9).
  3. Slice gives bytes. data[:3] is the bytes object b'caf'.
  4. Decode to text. decode("utf-8") rebuilds "café"; list() shows every byte value.

Example 3 — bytes Are Immutable: Errors and Workarounds

Try to change a byte, build a modified copy instead, and see the two most common construction errors.

python
packet = bytes([1, 2, 3])

try:
    packet[0] = 7
except TypeError:
    print("bytes cannot be changed in place")

changed = bytes([7]) + packet[1:]
print(changed)

try:
    bytes([300])
except ValueError:
    print("each value must be in range(0, 256)")

try:
    bytes("text")
except TypeError:
    print("a str needs an encoding")

How It Works

  1. No item assignment. packet[0] = 7 raises TypeError because bytes are immutable.
  2. Build a new object. Concatenating bytes([7]) with a slice creates a modified copy.
  3. Escapes for control bytes. 7, 2, and 3 are not printable, so the repr shows \x07\x02\x03.
  4. Construction errors. 300 does not fit in a byte (ValueError), and text needs an encoding (TypeError).

Frequently Asked Questions

str holds Unicode text; bytes holds raw values from 0 to 255. Convert with text.encode("utf-8") and data.decode("utf-8").
bytes is immutable and hashable, so it can be a dict key. bytearray is mutable and supports item assignment, append(), and extend().
Indexing a bytes object returns the byte value as an int. Slicing, such as data[0:1], returns a bytes object.
Use text.encode("utf-8") or bytes(text, "utf-8"). Both need an encoding.
Use bytes.fromhex("48 69"), which returns b'Hi'. data.hex() goes the other way.

Next: callable()

Check whether an object can be called like a function.

callable() →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

8 people found this page helpful