Python bytes(): Immutable Byte Sequences & Binary Encodings

The bytes() built-in function constructs an immutable sequence of integers in the range 0 ≤ x ≤ 255.

Binary Data & Wire Protocols: bytes objects represent raw machine-level memory buffers, file streams, and network packets. String inputs require an explicit encoding parameter, while integer counts allocate zero-filled buffers. For an editable in-place byte buffer, use companion constructor bytearray(). To convert binary data back to text or hexadecimal strings, see str() and hex().

1. Syntax & Formal Parameter Specifications 🔝

The bytes() constructor supports four distinct initialization patterns:

# Formal syntax of built-in bytes()
# Form 1: Zero-argument constructor
empty_bytes = bytes()

# Form 2: Integer count (creates zero-filled byte array)
zero_buffer = bytes(count)

# Form 3: String conversion with encoding and error policies
encoded_bytes = bytes(string, encoding='utf-8', errors='strict')

# Form 4: Iterable of integers (0 <= x <= 255)
seq_bytes = bytes(iterable_of_ints)
Parameter Type Accepted Behavioral Details
source int, str, Iterable[int], buffer Integer allocates zero-filled bytes; string requires encoding; iterable requires integers 0–255.
encoding str (optional) Encoding standard (e.g. 'utf-8', 'ascii'). Mandatory when source is a string.
errors str (optional) Error handling scheme: 'strict', 'ignore', 'replace'.
Return Value bytes object An immutable sequence of single bytes.

2. Basic Usage: Integers, Strings & Integer Lists 🔝

Passing an integer preallocates a buffer of null bytes (). When passing strings, specify the encoding:

# 1. Zero-filled byte allocation from an integer
zero_bytes = bytes(5)
print("bytes(5):           ", zero_bytes)        # b'\x00\x00\x00\x00\x00'
print("Length:             ", len(zero_bytes))   # 5

# 2. String encoding (encoding is REQUIRED for strings)
text = "plus2net.com"
encoded = bytes(text, encoding='utf-8')
print("bytes(str, 'utf-8'):", encoded)           # b'plus2net.com'
print("Type:               ", type(encoded))     # 

# 3. Iterable of integers (0-255)
byte_seq = bytes([65, 66, 67, 1, 2])
print("bytes([65, 66, 67]):", byte_seq)          # b'ABC\x01\x02'

Output:

bytes(5):            b'\x00\x00\x00\x00\x00'
Length:              5
bytes(str, 'utf-8'): b'plus2net.com'
Type:                
bytes([65, 66, 67]): b'ABC\x01\x02'

3. String Encodings & Error Handling Schemes 🔝

When strings contain characters outside the chosen character set, Python provides configurable error handlers:

# Handling non-ASCII characters with different error policies
raw_text = "plus2net.cÖm"

# strict: default mode, raises UnicodeEncodeError
try:
    bytes(raw_text, encoding='ascii', errors='strict')
except UnicodeEncodeError as err:
    print("strict error caught:", err)

# ignore: skips characters outside ASCII
b_ignore = bytes(raw_text, encoding='ascii', errors='ignore')
print("errors='ignore': ", b_ignore)   # b'plus2net.cm'

# replace: inserts ASCII question mark '?'
b_replace = bytes(raw_text, encoding='ascii', errors='replace')
print("errors='replace':", b_replace)  # b'plus2net.c?m'

Output:

strict error caught: 'ascii' codec can't encode character '\xd6' in position 10: ordinal not in range(128)
errors='ignore':  b'plus2net.cm'
errors='replace': b'plus2net.c?m'

4. Hexadecimal Conversions: bytes.fromhex() and .hex() 🔝

To construct byte buffers from hexadecimal strings or export raw bytes to hex, use bytes.fromhex() and .hex():

# Hexadecimal parsing via bytes.fromhex() and .hex() method
# bytes.fromhex() parses pairs of hex digits (spaces ignored)
raw_hex_data = bytes.fromhex('48 65 6c 6c 6f 21')
print("bytes.fromhex('48 65...'):", raw_hex_data)  # b'Hello!'

# Exporting back to hex string with .hex()
hex_str = raw_hex_data.hex()
print("raw_hex_data.hex():       ", hex_str)       # '48656c6c6f21'

Output:

bytes.fromhex('48 65...'): b'Hello!'
raw_hex_data.hex():        48656c6c6f21

5. bytes vs. bytearray: Immutability Comparison 🔝

Understanding the distinction between bytes and bytearray is essential for writing performant binary code:

Feature bytes bytearray
Mutability Immutable (read-only buffer) Mutable (in-place modification allowed)
Hashable / Dict Keys Yes (can be dictionary keys or set members) No (unhashable type)
In-Place Appending Requires reallocation and copy Supports .append(), .extend(), slice assignment
Best Used For Fixed headers, signatures, hash digests Accumulating network packets, streaming buffers
# bytes vs bytearray: immutability vs in-place mutation
b_fixed = bytes([65, 66, 67])       # b'ABC'
ba_mutable = bytearray([65, 66, 67]) # bytearray(b'ABC')

# Attempting mutation on bytes raises TypeError
try:
    b_fixed[0] = 90  # TypeError!
except TypeError as err:
    print("bytes mutation error:    ", err)

# bytearray can be modified in-place without reallocation
ba_mutable[0] = 90   # ASCII 'Z'
print("bytearray modified in-place:", ba_mutable)  # bytearray(b'ZBC')

Output:

bytes mutation error:     'bytes' object does not support item assignment
bytearray modified in-place: bytearray(b'ZBC')

6. Production Recipes & Practical Applications 🔝

Below are real-world recipes utilizing bytes for file header inspection and network packet construction:

# Recipe A: Binary file header validation (Magic Number check)
# PNG files always start with 8 magic bytes: 89 50 4E 47 0D 0A 1A 0A
PNG_MAGIC = bytes.fromhex("89504E470D0A1A0A")

def is_png_header(sample_bytes: bytes) -> bool:
    return sample_bytes.startswith(PNG_MAGIC)

header_sample = bytes.fromhex("89504E470D0A1A0A0000000D49484452")
print("Valid PNG header detected:", is_png_header(header_sample))

# Recipe B: Network packet framing with fixed-width packing
packet_opcode = 0x01
payload_data = b"DATA_SYNC"
packet = bytes([packet_opcode]) + payload_data
print("Framed network packet:", packet)

Output:

Valid PNG header detected: True
Framed network packet: b'\x01DATA_SYNC'

7. Common Pitfalls & Developer Traps 🔝

Frequent Traps with bytes()
  • Omitting String Encoding: Writing bytes("text") without an explicit encoding raises TypeError: string argument without an encoding. Always specify encoding="utf-8".
  • Integer Values Outside 0–255: Every element in a byte sequence must fit inside a single octet (0 to 255). Passing 256 or negative integers raises ValueError.
  • Indexing Returns Integers: Accessing a single byte via indexing b[0] returns an integer ordinal (e.g. 65), while slicing b[0:1] returns a 1-byte slice (b'A').
# Pitfall 1: Integers outside range 0-255 raise ValueError
try:
    bytes([256])  # Out of range!
except ValueError as err:
    print("ValueError caught:", err)

# Pitfall 2: Forgetting encoding parameter with strings
try:
    bytes("hello")  # TypeError!
except TypeError as err:
    print("TypeError caught: ", err)

Output:

ValueError caught: bytes must be in range(0, 256)
TypeError caught:  string argument without an encoding

8. Interactive Notebook & Practice Exercises 🔝

Practice immutable byte buffer construction, encoding policies, and magic number validations in our companion Jupyter Notebook:

Interactive Companion Jupyter Notebook

Explore interactive code cells, parse binary file signatures, decode multi-byte buffers, and run self-validating assertions.

View on GitHub Run in Google Colab

Self-Verifying Assertion Suite

Run these unit checks directly in Python or your local environment to verify bytes() mechanics:

def test_bytes_mechanics():
    # 1. Basic conversions
    assert bytes() == b""
    assert bytes(3) == b"\x00\x00\x00"
    assert bytes([65, 66]) == b"AB"
    assert bytes("hi", encoding="utf-8") == b"hi"
    
    # 2. Hex conversion
    assert bytes.fromhex("f1f2") == b"\xf1\xf2"
    assert b"\xf1\xf2".hex() == "f1f2"
    
    # 3. Immutability
    b = bytes([10, 20])
    try:
        b[0] = 99
        assert False, "Should raise TypeError"
    except TypeError:
        pass
        
    print("All bytes() unit assertions passed! 100% verified.")

test_bytes_mechanics()

Output:

All bytes() unit assertions passed! 100% verified.
bytearray()

Creates mutable, modifiable in-place array of bytes.

str()

Decodes binary byte buffers into human-readable text.

hex()

Converts integer numbers into hexadecimal string representations.

bin()

Converts integer numbers into binary string representations.




Subscribe to our YouTube Channel here



plus2net.com







Python Video Tutorials
Python SQLite Video Tutorials
Python MySQL Video Tutorials
Python Tkinter Video Tutorials
✖
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
© 2000-2026 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer