Python Bytes and Bytearray


In Python, bytes and bytearray are data types used to handle binary data. They are especially useful when working with files, network communications, or low-level data processing. While strings represent text data, bytes and bytearrays allow you to manipulate raw binary sequences efficiently.

This tutorial will cover the differences between bytes and bytearrays, how to create and manipulate them, and practical examples for real-world applications.

What Are Bytes in Python?

A bytes object is an immutable sequence of integers in the range 0–255. Each element in a bytes object represents a byte of data. Since bytes are immutable, you cannot modify them after creation.

Example:

data = b'Hello'
print(data)          # Output: b'Hello'
print(type(data))    # Output: <class 'bytes'>

Here:

  • The prefix b indicates that it is a bytes literal.

  • Each character in the string 'Hello' is converted into a byte using ASCII encoding.

What Are Bytearrays in Python?

A bytearray is similar to bytes but mutable, which means you can modify its elements after creation. Bytearrays are useful when you need to manipulate binary data dynamically.

Example:

data_array = bytearray(b'Hello')
print(data_array)        # Output: bytearray(b'Hello')
data_array[0] = 72       # ASCII for 'H' is 72
print(data_array)        # Output: bytearray(b'Hello')

Here, you can see that elements can be changed, unlike bytes, making bytearrays more flexible for certain operations.

Creating Bytes and Bytearrays

1. Using a Literal

b1 = b'Python'
ba1 = bytearray(b'Python')

2. Using the Constructor

b2 = bytes([65, 66, 67])          # Output: b'ABC'
ba2 = bytearray([65, 66, 67])     # Output: bytearray(b'ABC')

3. From a String with Encoding

text = "Hello"
b3 = bytes(text, 'utf-8')
ba3 = bytearray(text, 'utf-8')

Here, encoding converts a string into bytes or bytearray using a specific character encoding, such as utf-8 or ascii.

Accessing Elements

Bytes and bytearrays support indexing and slicing like lists or strings:

data = b'Python'
print(data[0])        # Output: 80 (ASCII of 'P')
print(data[1:4])      # Output: b'yt'

For bytearrays:

ba = bytearray(b'Python')
print(ba[0])          # Output: 80
ba[0] = 112           # Change 'P' to 'p'
print(ba)             # Output: bytearray(b'python')

Common Operations

Length of Bytes or Bytearray

b = b'Python'
ba = bytearray(b)
print(len(b))   # Output: 6
print(len(ba))  # Output: 6

Iterating Through Bytes or Bytearray

for byte in b:
    print(byte)  # Prints ASCII values

Concatenation

b1 = b'Hello'
b2 = b'World'
b3 = b1 + b2
print(b3)  # Output: b'HelloWorld'

For bytearrays:

ba1 = bytearray(b'Hello')
ba2 = bytearray(b'World')
ba1.extend(ba2)
print(ba1)  # Output: bytearray(b'HelloWorld')

Repeating Bytes

b = b'Hi' * 3
print(b)  # Output: b'HiHiHi'

Converting Between Bytes, Bytearray, and String

  1. Bytes to String:

b = b'Hello'
s = b.decode('utf-8')
print(s)  # Output: Hello
  1. String to Bytes:

s = "Hello"
b = s.encode('utf-8')
print(b)  # Output: b'Hello'
  1. Bytearray to Bytes:

ba = bytearray(b'Hello')
b = bytes(ba)
  1. Bytes to Bytearray:

b = b'Hello'
ba = bytearray(b)

These conversions are important when interacting with files or network sockets, as many APIs require bytes instead of strings.

Methods of Bytes and Bytearray

Common Methods for Bytes

  • b.upper(), b.lower()

  • b.startswith(), b.endswith()

  • b.find(), b.replace()

  • b.split()

Common Methods for Bytearray

Bytearrays support all the methods of bytes plus modification methods:

  • ba.append(x) – adds a byte at the end

  • ba.extend([x, y]) – adds multiple bytes

  • ba.insert(i, x) – inserts a byte at index i

  • ba.pop(i) – removes and returns a byte at index i

  • ba.remove(x) – removes the first occurrence of a byte

Practical Examples

  1. Reading a Binary File:

with open("example.bin", "rb") as file:
    data = file.read()
  1. Writing Bytes to a File:

with open("output.bin", "wb") as file:
    file.write(b'Hello Bytes')
  1. Converting String to Bytearray and Modifying:

ba = bytearray("Hello", "utf-8")
ba[0] = 104  # Change 'H' to 'h'
print(ba)    # Output: bytearray(b'hello')
  1. Concatenating Bytes:

b1 = b'Python '
b2 = b'Bytes'
b3 = b1 + b2
print(b3)  # Output: b'Python Bytes'
  1. Network Data Example:

data = b'\x48\x65\x6c\x6c\x6f'
print(data.decode('utf-8'))  # Output: Hello

Differences Between Bytes and Bytearray

Feature Bytes Bytearray
Mutability Immutable Mutable
Memory Efficiency Slightly higher Slightly lower
Modification Cannot modify Can modify elements
Use Case Fixed binary data Dynamic binary data

Summary of the Tutorial

Bytes and bytearrays are essential Python types for handling binary data efficiently. Bytes are immutable, ideal for read-only data or transmission, while bytearrays are mutable, allowing modifications. These data types are widely used in file handling, network communications, cryptography, and low-level data processing. Understanding how to create, manipulate, and convert between bytes, bytearrays, and strings is a key skill for working with Python in real-world applications.

Mastering bytes and bytearrays opens the door to efficient binary data processing and is a foundation for advanced programming tasks in networking and file management.


Practice Questions

  1. Create a bytes object containing the text "Python" and print it.

  2. Convert the string "Hello World" into bytes using UTF-8 encoding.

  3. Create a bytearray from the bytes object b'Python' and print it.

  4. Modify the first element of a bytearray b'Python' to change 'P' to 'p'.

  5. Append a new byte representing '!' to a bytearray.

  6. Concatenate two bytes objects: b'Hello ' and b'World'.

  7. Slice the bytes object b'PythonBytes' to get b'Bytes'.

  8. Convert a bytearray back into a string using UTF-8 decoding.

  9. Use the replace() method on a bytes object to replace b'Py' with b'Hi'.

  10. Read the first 10 bytes from a binary file and print them as a bytearray.


Try a Short Quiz.

Python Bytes and Bytearray Quiz

Finished the tutorial? Play this medium level quiz to strengthen your concepts.


Go Back Top