Python Bytes: Append & Extend, Explained with Examples!

The bytes class is a data structure 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. The bytes class is also immutable.

In this article, we’ll learn how to append an element to a bytes object and how to extend a bytes object.

Appending values to a bytes object

Firstly, let’s define what is appending;

Appending is when we add an item to the end of a data structure. 

embeddedinventor.com

For example, here’s this bytes object:

b'\x01\x02

If the above bytes object is appended with this byte: b’\x03′, 

This is what that would look like:

b'\x01\x02\x03'

Here’s a visual explanation:

Now let’s see how we can do this in code;

First of all, let’s recall that bytes is an immutable data type. This means that we can’t just add an element to the end of a bytes object by using a function like append()

Trying something like that will only lead to an error:

my_bytes = bytes([1,2]) #b'\x01\x02'
print(my_bytes)

my_bytes.append(3)
b'\x01\x02'
Traceback (most recent call last):
  File "/home/main.py", line 4, in <module>
    my_bytes.append(3)
AttributeError: 'bytes' object has no attribute 'append'

How we can get around this limitation is that we can reassign a value to the my_bytes object and add an element in the process:

my_bytes = bytes([1,2]) #b'\x01\x02'
print(my_bytes)

my_bytes = my_bytes + bytes([3]) #or my_bytes += bytes([3])
print(my_bytes)
b'\x01\x02'
b'\x01\x02\x03'

In this process, we are essentially

  1. creating a new bytes object
  2. assigning it new values and finally
  3. rewriting it on our bytes object. 

Here’s a visualization of the same:

From the example, we see the syntax is as follows:

arrayName = arrayName  + element
  1. arrayName – The name of the bytes object to which you want to append the element.
  2. element – The element to be appended to the bytes object. This element must always be of bytes datatype.

Here’s another example where we add elements one by one to an empty bytes object.

#creating an empty Bytes array
my_bytes = bytes()

my_bytes += bytes([104]) #ascii code for 'h'
my_bytes += bytes([105]) #ascii code for 'i'
my_bytes += bytes([33])  #ascii code for '!'

print(my_bytes)
b'hi!'

Note: Read here to know more about how we can add letters using the ASCII code

If you are planning to do more than one edit on a bytes object, instead of following the workaround explained above it is recommended that you use its editable cousin the bytearray. If you wish to learn more I suggest reading our article on bytearray in the link below.

Python: bytearray vs bytes, Similarities & Differences Explained!

Also, here is a YouTube video we made on ByteArray if you wish to learn more!

Extending values to a bytes object

Extending a bytes object is simply when you combine one bytes object with another bytes object.

embeddedinventor.com

To extend a bytes object with another bytes object, we can follow the same procedure we did for appending.

myArray = bytes([1,2,3])

myOtherArray = bytes([4, 5, 6])
print(myOtherArray) #b'\x04\x05\x06'

myArray += myOtherArray
print(myArray) #b'\x01\x02\x03\x04\x05\x06'

As you can see, all the elements from the bytes object myOtherArray (“4”, “5”, and “6”) got added to the end of the 1st array. 

Here’s a visual explanation of the process:

Here is one more example of using this syntax

my_array = bytearray('Hello my name is John ', 'utf-8')
my_age_array = bytearray('I am 33 years old', 'utf-8')

#extending the bytearray
my_array += my_age_array 

print(my_array)
bytearray(b'Hello my name is John I am 33 years old')

There are tons of methods available for working with bytes objects, if you wish to learn more I suggest reading our comprehensive article on the bytes class mentioned below.

Python Bytes: Everything you need to know!

And that’s a wrap, folks!

Kudos to you for reading the whole thing, only a few have the patience to do so!

I hope you enjoyed reading this article and found this article helpful!

Also, 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: bytearray vs bytes, Similarities & Differences Explained!

Python ByteArray: Everything you need to know!

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