bytes()

bytes([source[, encoding[, errors]]])
Returns: bytes · Added in v3.0 · Updated March 13, 2026 · Built-in Functions
built-in binary immutable bytes

The bytes function returns an immutable bytes object. Unlike bytearray, which is mutable, bytes objects cannot be modified after creation. This makes them suitable for representing fixed binary data such as file contents, network packets, or encoded text.

Syntax

bytes(source)
bytes(source, encoding)
bytes(source, encoding, errors)

Parameters

ParameterTypeDefaultDescription
sourceint | iterable | str | bytes-likeThe source data to convert to bytes.
encodingstr"utf-8"Encoding to use when source is a string.
errorsstr"strict"How to handle encoding errors.

Returns: An immutable bytes object.

Examples

Creating an empty bytes object

# Empty bytes
empty = bytes()
print(empty)
# b''

# Create bytes of a specific length
zero_bytes = bytes(5)
print(zero_bytes)
# b'\x00\x00\x00\x00\x00'

From an iterable of integers

# Each integer must be 0-255
b = bytes([72, 101, 108, 108, 111])
print(b)
# b'Hello'

# Numbers outside 0-255 raise ValueError
bytes([256])
# ValueError: bytes must be in range(0, 256)

From a string with encoding

# Encode a string to bytes
text = "Hello"
b = text.encode('utf-8')
print(b)
# b'Hello'

# Using bytes() constructor directly
b = bytes('Hello', 'utf-8')
print(b)
# b'Hello'

From other bytes-like objects

# From a bytes object (copy)
original = b'Hello'
copied = bytes(original)
print(copied)
# b'Hello'

# From bytearray
ba = bytearray(b'World')
b = bytes(ba)
print(b)
# b'World'

Working with different encodings

# UTF-8 (default)
text = "Python"
print(bytes(text, 'utf-8'))
# b'Python'

# Latin-1 (ISO-8859-1)
text = "Café"
print(bytes(text, 'latin-1'))
# b'Caf\xe9'

# ASCII
text = "Hello"
print(bytes(text, 'ascii'))
# b'Hello'

Common Patterns

Reading binary files

# Read file as bytes
with open('image.png', 'rb') as f:
    image_data = bytes(f.read())
    print(len(image_data))

Network programming

# HTTP request as bytes
request = b"GET / HTTP/1.1\r\nHost: example.com\r\n\r\n"
print(request)
# b'GET / HTTP/1.1...'

Working with hex

# Convert bytes to hex
data = b'Hello'
hex_string = data.hex()
print(hex_string)
# 48656c6c6f

# Convert hex to bytes
original = bytes.fromhex('48656c6c6f')
print(original)
# b'Hello'

Slicing bytes

# Bytes objects support slicing
data = b'Hello World'
print(data[0:5])
# b'Hello'
print(data[6:])
# b'World'
print(data[::2])
# b'HloWrd'

Errors

ValueError from invalid integer

# Integer must be non-negative
bytes(-1)
# ValueError: negative count

# Must be in valid range
bytes([300])
# ValueError: bytes must be in range(0, 256)

UnicodeDecodeError

# Invalid UTF-8 sequence
bytes([200, 200])  # Invalid UTF-8
# UnicodeDecodeError when decoding

See Also