# Python bytearray() Function

5/5 - (3 votes)

Python’s built-in bytearray() method takes an iterable such as a list of integers between 0 and 256, converts them to bytes between 00000000 and 11111111, and returns a new array of bytes as a bytearray class.

Here’s a minimal example that creates a bytearray from three integers stored in a list:

>>> bytearray([1, 2, 3])
bytearray(b'\x01\x02\x03')

The prefix \x escape sequence means the next two characters are interpreted as hex character codes. For instance, the hex code \x01 is the same as chr(0x01)=16*0+1=1 that’s simply a start of heading SOH character. (source, ASCII table)

Syntax: bytearray([source[, encoding[, errors]]])

Here are some basic usages of the function:

Input : bytearray(4)
Output : bytearray(b'\x00\x00\x00\x00')

Input : bytearray([1, 2, 3])
Output : bytearray(b'\x01\x02\x03')

Input : bytearray('hi', 'UTF-8')
Output : bytearray(b'hi')

Want to learn more, we’re going to dive into more examples next!

Check out my new Python book Python One-Liners (Amazon Link).

If you like one-liners, you’ll LOVE the book. It’ll teach you everything there is to know about a single line of Python code. But it’s also an introduction to computer science, data science, machine learning, and algorithms. The universe in a single line of Python!

The book was released in 2020 with the world-class programming book publisher NoStarch Press (San Francisco).

## Create Bytearray From Single Integer Argument — Examples

The following code shows you how to use the bytearray() function on simple integer arguments.

# Single Integer Input Argument
print(bytearray())
print(bytearray(2))
print(bytearray(4))

'''
bytearray(b'')
bytearray(b'\x00\x00')
bytearray(b'\x00\x00\x00\x00')
'''

If you provide only one input argument, it uses this input argument to determine how many bytes should be created. It just uses bytes with value 0, in byte notation \x00 to fill the bytearray.

## Create ByteArray From Iterable of Integers — Examples

You can also provide an iterable argument to obtain a new bytearray:

# Iterable Input Argument
print(bytearray([1, 1, 1]))
print(bytearray([14]))
print(bytearray({9, 8, 7}))

'''
bytearray(b'\x01\x01\x01')
bytearray(b'\x0e')
bytearray(b'\x08\t\x07')
'''

The iterable must consist of a number of integers between 0 and 256. If you fail to do so, Python will throw a ValueError:

## How to Fix “ValueError: byte must be in range(0, 256)”

If you use the bytearray() function on an iterable that contains at least one integer greater than the maximum number representable by 8 bits, namely 256, or smaller than 0, Python will throw a ValueError: byte must be in range(0, 256). You can fix it by ensuring that each number in your iterable can actually be represented by 8 bits and falls into the interval 0 to 256.

Here’s an example of the ValueError where you use a number larger or equal than 256:

>>> bytearray([999])
Traceback (most recent call last):
File "<pyshell#6>", line 1, in <module>
bytearray([999])
ValueError: byte must be in range(0, 256)

Another example when using a number smaller than 0:

>>> bytearray([-10])
Traceback (most recent call last):
File "<pyshell#8>", line 1, in <module>
bytearray([-10])
ValueError: byte must be in range(0, 256)

Fix it by modifying the numbers to lie within the interval 0 to 256:

>>> bytearray([255])
bytearray(b'\xff')

## Summary

Python’s built-in bytearray() function allows you to create a new bytearray an intialize it in four different ways (from simple to more complex):

👉 integer –> array has this size and is initialized with 0 bytes:

>>> bytearray(4)
bytearray(b'\x00\x00\x00\x00')

👉 iterable –> integers in the range 0 <= x < 256 are initial bytearray contents:

>>> bytearray([1, 2, 3])
bytearray(b'\x01\x02\x03')

👉 string and you provide the encoding (and optionally, errors) arguments –> bytearray() converts string to bytes using str.encode().

>>> bytearray('hi', 'UTF-8')
bytearray(b'hi')

👉 object implementing the buffer interface –> initializes the bytes array via a read-only object buffer.

🌍 Recommended Tutorial: Python Bytes vs ByteArray

Do you want to boost your Python skills in a fun and easy-to-consume way? Consider the following resources and become a master coder!

## Where to Go From Here?

Enough theory. Let’s get some practice!

Coders get paid six figures and more because they can solve problems more effectively using machine intelligence and automation.

To become more successful in coding, solve more real problems for real people. That’s how you polish the skills you really need in practice. After all, what’s the use of learning theory that nobody ever needs?

You build high-value coding skills by working on practical coding projects!

Do you want to stop learning with toy projects and focus on practical code projects that earn you money and solve real problems for people?

🚀 If your answer is YES!, consider becoming a Python freelance developer! It’s the best way of approaching the task of improving your Python skills—even if you are a complete beginner.

If you just want to learn about the freelancing opportunity, feel free to watch my free webinar “How to Build Your High-Income Skill Python” and learn how I grew my coding business online and how you can, too—from the comfort of your own home.

Join the free webinar now!