What’s the Difference Between bytes() and bytearray()?
The difference between
bytearray() is that
bytes() returns an immutable and
bytearray() returns a mutable object. So you can modify a
bytearray but not
Here’s a minimal example that nicely demonstrates the difference of the two functions:
>>> a = bytes(3) >>> b = bytearray(3) >>> a b'\x00\x00\x00' >>> b bytearray(b'\x00\x00\x00') >>> a = 1 Traceback (most recent call last): File "<pyshell#16>", line 1, in <module> a = 1 TypeError: 'bytes' object does not support item assignment >>> b = 1 >>> b bytearray(b'\x01\x00\x00')
You create two variables
b. The former is a
bytes and the latter a
bytearray—both encoding the same data.
However, if you try to modify the
bytes object, Python raises a
TypeError: 'bytes' object does not support item assignment.
You resolve the error by using a
bytearray object instead — if you modify it using item assignment such as
b = 1, the error disappears.
The reason is that unlike
bytearray type is mutable.
🌍 Recommended Tutorial: Python Mutable vs Immutable Objects
Let’s recap both functions quickly. Afterward, we will do a performance comparison in case you wondered which is faster!
bytes(source) function creates an immutable
bytes object initialized as defined in the function argument
A bytes object is like a string but it uses only byte characters consisting of a sequence of 8-bit integers in the range
The returned byte object is immutable—you cannot change it after creation. If you plan to change the contents, use the
bytearray() method to create a mutable
# Single Integer Input Argument print(bytes()) print(bytes(2)) print(bytes(4)) ''' b'' b'\x00\x00' b'\x00\x00\x00\x00' '''
🌍 Recommended Tutorial: Python
bytes() Built-in Function
bytearray() function takes an iterable such as a list of integers between 0 and 256, converts them to bytes between
11111111, and returns a new array of bytes as a
# Single Integer Input Argument print(bytearray()) print(bytearray(2)) print(bytearray(4)) ''' bytearray(b'') bytearray(b'\x00\x00') bytearray(b'\x00\x00\x00\x00') '''
🌍 Recommended Tutorial: Python
bytearray() Built-in Function
Performance bytes() vs bytearray()
Creating a large
bytes object (e.g., 100 million bytes) using
bytes() is faster than creating a
bytearray() because the mutability of the latter comes at a performance cost.
In our experiment creating objects of 100 million bytes, we have seen a performance speedup of 3x using
bytes() compared to
Here’s the code of the simple experiment setup:
import time n = 100000000 start = time.time() b = bytes(b'x' * n) stop = time.time() print('bytes()', stop - start) start = time.time() b = bytearray(b'x' * n) stop = time.time() print('bytearray()', stop - start)
I ran the experiment multiple times on my Win Intel Core i7 CPU with 8GB of RAM and obtained the following output:
= RESTART: bytes() 0.02437591552734375 bytearray() 0.07250618934631348 >>> = RESTART: bytes() 0.015362262725830078 bytearray() 0.0646059513092041 >>> = RESTART: bytes() 0.017394542694091797 bytearray() 0.05153799057006836 >>> = RESTART: bytes() 0.013019084930419922 bytearray() 0.0436251163482666 >>> = RESTART: bytes() 0.011996746063232422 bytearray() 0.042777299880981445
So the difference is roughly 3-4x in performance:
bytes() is 300-400% faster than
However, don’t let this tiny performance edge fool you!
It’s better to ignore this fact and optimize for readability and suitability to the problem at hand.
- Do you need to change the data structure holding bytes after creation? Use the mutable
- Do you create the data structure once and then only read its information? Use the immutable
In all cases, don’t do premature optimization!
👉 Recommended Tutorial: Premature Optimization is the Root of All Evil
Where to Go From Here?
Thanks for reading the whole tutorial—I hope you got some valuable pieces of knowledge out of it.
If you want to keep improving your coding skills and become a Python pro, check out our free email academy. We have cheat sheets too!
While working as a researcher in distributed systems, Dr. Christian Mayer found his love for teaching computer science students.
To help students reach higher levels of Python success, he founded the programming education website Finxter.com that has taught exponential skills to millions of coders worldwide. He’s the author of the best-selling programming books Python One-Liners (NoStarch 2020), The Art of Clean Code (NoStarch 2022), and The Book of Dash (NoStarch 2022). Chris also coauthored the Coffee Break Python series of self-published books. He’s a computer science enthusiast, freelancer, and owner of one of the top 10 largest Python blogs worldwide.
His passions are writing, reading, and coding. But his greatest passion is to serve aspiring coders through Finxter and help them to boost their skills. You can join his free email academy here.