Python Bytes and Bytearray


In Python, bytes and bytearray are used to handle binary data.
They look like lists of integers but represent data in bytes form (0 to 255).


🔹 Bytes – Immutable Binary Data

data = bytes([65, 66, 67])
print(data)         # b'ABC'
print(data[0])      # 65

✅ You cannot change values in a bytes object.


🔹 Bytearray – Mutable Binary Data

data = bytearray([65, 66, 67])
print(data)         # bytearray(b'ABC')
data[1] = 90
print(data)         # bytearray(b'AZC')

✅ You can change values in a bytearray.


🔹 From String to Bytes

text = "hello"
b = bytes(text, 'utf-8')
print(b)  # b'hello'

🔹 From Bytes to String

b = b'hello'
text = b.decode('utf-8')
print(text)  # hello

🔹 Convert to Bytearray

b = b"data"
ba = bytearray(b)

🔹 Useful Methods

Method Works On Description
.decode() bytes Converts to string
.append(x) bytearray Adds one byte to the end
.pop() bytearray Removes the last byte
.reverse() bytearray Reverses byte order
.extend([]) bytearray Adds multiple bytes

🔹 Use Case: Binary Files

with open("file.bin", "rb") as f:
    content = f.read()
    print(content)  # bytes

🧪 Try It Yourself

  • Convert string to bytes

  • Modify bytearray data

  • Decode bytes into text

  • Use .append() or .reverse() on bytearray


Practice Questions

Q1. Write a Python program to create a bytes object with values [65, 66, 67] and print it.

Q2. Write a Python program to print the second byte from a bytes object.

Q3. Write a Python program to try changing a byte in a bytes object and observe the error (bytes are immutable).

Q4. Write a Python program to create a bytearray and modify the first element.

Q5. Write a Python program to convert the string "Python" into bytes using UTF-8 encoding.

Q6. Write a Python program to decode b'Hello' into a string using .decode().

Q7. Write a Python program to append the value 88 to a bytearray using append().

Q8. Write a Python program to use .reverse() on a bytearray and print the result.

Q9. Write a Python program to convert a bytes object to a bytearray and modify its content.

Q10. Write a Python program to read a binary file and print its content in bytes.


Go Back Top