Last modified: Mar 25, 2026 By Alexander Williams

Python Bytes Array Guide: Create & Manipulate

Python handles binary data with special objects. The main ones are bytes and bytearray. They are like lists but for numbers from 0 to 255.

This guide explains these objects. You will learn how to create, change, and use them. This is key for files, networks, and data processing.

What is a Bytes Object?

A bytes object is immutable. This means you cannot change it after creation. It is a sequence of integers. Each integer is between 0 and 255.

Think of it as a tuple for byte values. It is perfect for data that should not be altered. This includes reading a file or receiving network data.

You create it with the bytes() constructor or the b'' literal syntax.


# Creating bytes objects
# Using a literal
data = b'Hello'
print(f"Literal bytes: {data}")
print(f"Type: {type(data)}")

# Using the bytes constructor from a list
byte_list = [72, 101, 108, 108, 111]  # ASCII for 'Hello'
bytes_from_list = bytes(byte_list)
print(f"Bytes from list: {bytes_from_list}")

# Using bytes with a length (all zeros)
empty_bytes = bytes(5)
print(f"Empty bytes of length 5: {empty_bytes}")
    

Literal bytes: b'Hello'
Type: 
Bytes from list: b'Hello'
Empty bytes of length 5: b'\x00\x00\x00\x00\x00'
    

What is a Bytearray Object?

A bytearray object is mutable. You can change its contents after creation. It is like a list for byte values.

Use it when you need to modify binary data. This includes building a packet or editing an image.

You create it with the bytearray() constructor.


# Creating a mutable bytearray
mutable_data = bytearray(b'World')
print(f"Original bytearray: {mutable_data}")

# You can change it
mutable_data[0] = 119  # ASCII 'w' is 119
print(f"After modification: {mutable_data}")

# Append a new byte
mutable_data.append(33)  # ASCII '!' is 33
print(f"After append: {mutable_data}")
    

Original bytearray: bytearray(b'World')
After modification: bytearray(b'world')
After append: bytearray(b'world!')
    

Key Operations on Bytes and Bytearray

Both types support common sequence operations. You can access elements, get the length, and slice them. For a deeper look at accessing elements, see our Python Array Indexing Guide for Beginners.

Accessing and Slicing

You use indexing and slicing, just like with lists or strings. Slicing is a powerful way to extract parts of your data. Learn all about it in our Python Array Slicing: A Complete Guide.


data = b'Python Bytes'

# Indexing
first_byte = data[0]
print(f"First byte (value): {first_byte}")
print(f"First byte (as char): {chr(first_byte)}")

# Slicing
slice_1 = data[0:6]
slice_2 = data[7:]
print(f"Slice [0:6]: {slice_1}")
print(f"Slice [7:]: {slice_2}")

# Finding length
length = len(data)
print(f"Length of data: {length}")
    

First byte (value): 80
First byte (as char): P
Slice [0:6]: b'Python'
Slice [7:]: b'Bytes'
Length of data: 12
    

Iteration and Conversion

You can loop over bytes. You can also convert them to and from other types.


byte_data = b'ABC'

# Iteration
print("Iterating over bytes:")
for byte in byte_data:
    print(f"  Byte value: {byte}, Character: {chr(byte)}")

# Convert bytes to a list of integers
list_from_bytes = list(byte_data)
print(f"Bytes as list: {list_from_bytes}")

# Convert a list back to bytes
new_bytes = bytes([88, 89, 90])  # XYZ
print(f"New bytes from list: {new_bytes}")
    

Iterating over bytes:
  Byte value: 65, Character: A
  Byte value: 66, Character: B
  Byte value: 67, Character: C
Bytes as list: [65, 66, 67]
New bytes from list: b'XYZ'
    

Common Use Cases

Bytes and bytearray are essential for many tasks.

Reading and Writing Binary Files

You must use binary mode ('rb' or 'wb') for non-text files.


# Writing bytes to a file
data_to_write = b'\x89PNG\r\n\x1a\n'  # PNG file header
with open('sample.bin', 'wb') as f:
    f.write(data_to_write)
print("Wrote bytes to 'sample.bin'")

# Reading bytes from a file
with open('sample.bin', 'rb') as f:
    read_data = f.read(8)  # Read first 8 bytes
print(f"Read from file: {read_data}")
    

Wrote bytes to 'sample.bin'
Read from file: b'\x89PNG\r\n\x1a\n'
    

Network Communication

Data sent over networks is often raw bytes. Sockets use bytes for sending and receiving.


# Simulating a network packet
packet_header = bytearray([0x10, 0x20, 0x00, 0x05])  # Header bytes
packet_payload = b'Hello'
full_packet = packet_header + packet_payload

print(f"Full packet (bytes): {full_packet}")
print(f"Packet length: {len(full_packet)}")
    

Full packet (bytes): bytearray(b'\x10 \x00\x05Hello')
Packet length: 9
    

Data Encoding and Decoding

Use the decode() method to convert bytes to a string. Use encode() on a string to get bytes.


# String to bytes (encoding)
text = "Python Guide"
encoded_bytes = text.encode('utf-8')
print(f"Encoded bytes: {encoded_bytes}")

# Bytes to string (decoding)
decoded_text = encoded_bytes.decode('utf-8')
print(f"Decoded text: {decoded_text}")
    

Encoded bytes: b'Python Guide'
Decoded text: Python Guide
    

Bytes vs. Lists and Arrays

It is important to know the difference. A bytes object is not a standard Python list. For a detailed comparison, check out Python Array vs List: Key Differences Explained.

Bytes/Bytearray store numbers from 0-255. They are compact and for binary data.

Lists can store any data type. They are more flexible but use more memory.

Array module stores uniform numeric types. It is more efficient than a list for numbers.


import array

# Comparing structures
byte_seq = b'\x01\x02\x03'
list_seq = [1, 2, 3]
arr_seq = array.array('B', [1, 2, 3])  # 'B' for unsigned char

print(f"Bytes: {byte_seq}, Type: {type(byte_seq)}")
print(f"List: {list_seq}, Type: {type(list_seq)}")
print(f"Array: {arr_seq}, Type: {type(arr_seq)}")
    

Bytes: b'\x01\x02\x03', Type: 
List: [1, 2, 3], Type: 
Array: array('B', [1, 2, 3]), Type: 

Important Methods to Remember

Here are key methods for bytes and bytearray.

  • fromhex(): Creates a bytes object from a hex string.
  • hex(): Returns a hex string representation.
  • find(): Finds a sub-sequence of bytes.
  • replace(): Replaces occurrences of a byte pattern (returns new bytes).
  • append(): (Bytearray only) Adds a byte to the end.
  • extend(): (Bytearray only) Adds multiple bytes.

# Using hex methods
hex_string = "48656c6c6f"  # 'Hello' in hex
bytes_from_hex = bytes.fromhex(hex_string)
print(f"From hex: {bytes_from_hex}")

back_to_hex = bytes_from_hex.hex()
print(f"Back to hex: {back_to_hex}")

# Using find and replace
data = b"Hello World Hello"
pos = data.find(b"World")
print(f"Found 'World' at index: {pos}")

new_data = data.replace(b"Hello", b"Hi")
print(f"After replace: {new_data}")
    

From hex: b'Hello'
Back to hex: 48656c6c6f
Found 'World' at index: 6
After replace: b'Hi World Hi'
    

Conclusion

Python's bytes and bytearray are vital for binary data. Use immutable bytes for safe, read-only data. Use mutable bytearray when you need to modify the data.

They are the foundation for file I/O, networking, and data serialization. Mastering them unlocks low-level programming in Python.

Remember the key difference: bytes cannot be changed, bytearray can. Choose the right tool for your task. Start using them in your next project that handles raw data.