Home Python Built-in Functions bytes() Python bytes() Function 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.
empty = bytes(3) # b'\x00\x00\x00'
data = bytes([72, 105]) # b'Hi'
encoded = bytes("Hi", "utf-8") # b'Hi' Call What 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 bytes(source=b"")
bytes(source, encoding, errors="strict")
# class bytes: an immutable built-in type Parameters Parameter Description source Optional. An int (size), an iterable of ints 0-255, a bytes-like object, or a str (requires encoding). encoding Required when source is a str. A codec such as "utf-8". errors Optional. What to do with characters the encoding cannot represent. Default "strict".
Return Value Return Value Description bytes A new immutable bytes object.
Important
A str without an encoding raises TypeError; values outside 0-255 raise ValueError. Because bytes are immutable, item assignment raises TypeError; build a new object or use bytearray. Note that len() counts bytes, not characters.
Python Examples 1. Create bytes 2. Encode and index 3. Immutability and errors 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.
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))) b'\x00\x00\x00'
b'Hi!'
b'Hi!'
True
b'ABCDE' How It Works Size gives zeros. bytes(3) creates three bytes with value 0, shown as \x00.From ints. 72, 105, and 33 are the ASCII codes for H, i, and !.From text. Encoding "Hi!" as UTF-8 produces exactly the same bytes, and they compare equal to the literal.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.
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)) b'caf\xc3\xa9'
4 5
99 169
b'caf'
'caf\xe9'
[99, 97, 102, 195, 169] How It Works Two bytes for é. UTF-8 stores é as C3 A9, so 4 characters become 5 bytes.Index gives an int. data[0] is 99 (the letter c) and data[-1] is 169 (0xA9).Slice gives bytes. data[:3] is the bytes object b'caf'.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.
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") bytes cannot be changed in place
b'\x07\x02\x03'
each value must be in range(0, 256)
a str needs an encoding How It Works No item assignment. packet[0] = 7 raises TypeError because bytes are immutable.Build a new object. Concatenating bytes([7]) with a slice creates a modified copy.Escapes for control bytes. 7, 2, and 3 are not printable, so the repr shows \x07\x02\x03.Construction errors. 300 does not fit in a byte (ValueError), and text needs an encoding (TypeError).Frequently Asked Questions What is the difference between bytes and str? str holds Unicode text; bytes holds raw values from 0 to 255. Convert with text.encode("utf-8") and data.decode("utf-8").
What is the difference between bytes and bytearray? bytes is immutable and hashable, so it can be a dict key. bytearray is mutable and supports item assignment, append(), and extend().
Why does data[0] return an int? Indexing a bytes object returns the byte value as an int. Slicing, such as data[0:1], returns a bytes object.
How do I convert a str to bytes? Use text.encode("utf-8") or bytes(text, "utf-8"). Both need an encoding.
How do I create bytes from hex? 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 Developer, cloud engineer, and technical writer
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
Helpful Share Copy link Suggestion