Python: bytearray vs bytes, Similarities & Differences Explained!

In this article, we’ll have a look at all the differences between the 2 very similar classes bytearray and bytes and learn how they relate to each other.

I remember the time when I first came across these 2 classes of Python, at the beginning I thought they were one and the same, but as I got more familiar with these classes I started to notice some subtle differences, this article is all about learning their similarities and differences and learning what makes them unique.

In particular, we will be looking at the following properties of these 2 classes

  • Mutability
  • Use cases (when to use which one?)
  • Performance &
  • Supported methods

We’ll also be looking at some interesting examples along the way, so without further ado let’s dive in!

For those of you in a hurry here is the short version of the answer.

To keep it really short, if you are familiar with the difference between tuple and list datastructures in Python, you can think of bytearray as a list and bytes as a tuple that can only hold integers (0,255)

Don’t worry if the above explanation does not make sense to you as that was targeted at more experienced programmers who just wanted to refresh their memories. The rest of this article is dedicated to those of you in the first steps of your journey to becoming a Python Craftsman.

By the time you reach the end of this article, I suggest you come back and read this summary once more, I assure you it will make much more sense then!

Let us start by looking at some of the fundamental concepts that define bytes and bytearray classes.

The Fundamentals

Both the bytes class and the bytearray class are data structures in Python that can be used when we wish to store a collection of bytes in an ordered manner in a contiguous area of memory.

Covering everything you need to know about these 2 classes is beyond the scope of this article, fear not as we have 2 nice articles explaining each of them in detail, that you can find in the links below!

Python Bytes: Everything you need to know!

Python ByteArray: Everything you need to know!

Now that we have the fundamentals in place, let us continue our discussion with the main difference between the 2 classes, which lies in the mutability property.

Mutability

The primary difference between bytearray and bytes is that bytearray is a mutable type whereas bytes is an immutable type. In other words, a bytearray object can be changed after creation but you cannot change a bytes object once you have created them!

If the concepts of an object being “mutable” and “immutable” is not familiar to you, then I suggest reading our other article on that topic. You can find that in the link below.

Mutable and Immutable Data Types in python explain using examples

Let’s have a look at an example.

# creating a bytearray object
my_bytearray = bytearray(5)
print(my_bytearray) # prints bytearray(b'\x00\x00\x00\x00\x00')

# creating a bytes object
my_bytes = bytes(5)
print(my_bytes)

# changing a bytearray object
my_bytearray[0] = 5
print(my_bytearray) # prints bytearray(b'\x05\x00\x00\x00\x00')

# changing a bytes object
my_bytes[0] = 5
print(my_bytes) # leads to an error

The above example shows how the bytearray object can be easily modified without any issues but we if try to modify the bytes object, it raises an error as it is not mutable.

The only way to edit the data inside a bytes object is to first copy it onto a bytearray, then edit it, then copy it back into another bytes object as shown below

# Here’s a byte object for instance:
a = bytes(3)

# We convert it into a bytearray object::
b = bytearray(a)

# And modify it:
b[1] = 5

# Finally, convert it back to a bytes object:
c = bytes(b)

Here’s how the full code would look like:

a = bytes(3)
print("Before modification:", a)

b = bytearray(a)
b[1] = 5

c = bytes(b)
print("After modification:", c)
Before modification: b'\x00\x00\x00'
After modification: b'\x00\x05\x00'

Keep in mind that variable a and c above are not the same object!

If all this is confusing to you then once again I recommend reading our article on mutability!

Mutable and Immutable Data Types in python explain using examples

When to use which one? bytes vs bytearray

If you are not sure which one to use when, then keep the following rule in mind.

  • If you wish to edit something in-place then use bytearray
  • If you wish to pass on your data to some other function, which should not modify the data, then use the bytes object.

This is true not only for bytes and bytearray types, but for any mutable and immutable types!

Performance

Let’s look at another difference between bytes and bytearray. Did you know that a bytes object is faster to create than a bytearray object?  Yes, and that’s because a bytearray object is mutable hence it takes a toll on the performance.
Have a look at this experiment that compares the creation of bytes and bytearray objects of 1 billion bytes.

Supported Methods

The bytearray class has several methods that the bytes class does not support. For instance, we can use the append() function to add an element to the end of the data structure in bytearray class

my_nums = [1,2,3,4]
a = bytearray(my_nums)
print(a)

a.append(5)
print(a)

This is not possible to do with the bytes class as it does not support any append() function since it is immutable. It will only raise a TypeError

my_nums = [1,2,3,4]
a = bytes(my_nums)
print(a)

a.append(5)
print(a)

Here’s a full list of functions that bytearray class supports but bytes class doesn’t:

  • append
  • clear
  • copy
  • extend
  • insert
  • pop
  • remove
  • reverse

You can find out more about these functions here with detailed explanations.

If you haven’t already, I invite you to watch our YouTube video that we made on ByteArray!

And with that, I will end this article.

Congratulations on making it to the end of the article, not many have the perseverance to do so!

I hope you enjoyed reading this article and found it useful!

Feel free to share it with your friends and colleagues!

If your thirst for knowledge has not been quenched yet, here are some related articles that might spark your interest!

Related Articles

Python Bytes: Everything you need to know!

Python ByteArray: Everything you need to know!

Mutable and Immutable Data Types in python explain using examples

Thanks to Namazi Jamal for his contributions in writing this article!

Photo of author
Editor
Balaji Gunasekaran
Balaji Gunasekaran is a Senior Software Engineer with a Master of Science degree in Mechatronics and a bachelor’s degree in Electrical and Electronics Engineering. He loves to write about tech and has written more than 300 articles. He has also published the book “Cracking the Embedded Software Engineering Interview”. You can follow him on LinkedIn