What is byte array in python

In this tutorial, we will learn about the Python bytearray() method with the help of examples.

The bytearray() method returns a bytearray object which is an array of the given bytes.

Example

prime_numbers = [2, 3, 5, 7]

# convert list to bytearray byte_array = bytearray(prime_numbers)

print(byte_array) # Output: bytearray(b'\x02\x03\x05\x07')


bytearray() Syntax

The syntax of bytearray() method is:

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

bytearray() method returns a bytearray object (i.e. array of bytes) which is mutable (can be modified) sequence of integers in the range 0 <= x < 256.

If you want the immutable version, use the bytes() method.


bytearray() Parameters

bytearray() takes three optional parameters:

  • source (Optional) - source to initialize the array of bytes.
  • encoding (Optional) - if the source is a string, the encoding of the string.
  • errors (Optional) - if the source is a string, the action to take when the encoding conversion fails (Read more: String encoding)

The source parameter can be used to initialize the byte array in the following ways:

TypeDescription
String Converts the string to bytes using str.encode() Must also provide encoding and optionally errors
Integer Creates an array of provided size, all initialized to null
Object A read-only buffer of the object will be used to initialize the byte array
Iterable Creates an array of size equal to the iterable count and initialized to the iterable elements Must be iterable of integers between 0 <= x < 256
No source (arguments) Creates an array of size 0.


bytearray() Return Value

The bytearray() method returns an array of bytes of the given size and initialization values.


Example 1: Array of bytes from a string

string = "Python is interesting."

# string with encoding 'utf-8' arr = bytearray(string, 'utf-8')

print(arr)

Output

bytearray(b'Python is interesting.')

Example 2: Array of bytes of given integer size

size = 5

arr = bytearray(size)

print(arr)

Output

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

Example 3: Array of bytes from an iterable list

rList = [1, 2, 3, 4, 5]

arr = bytearray(rList)

print(arr)

Output

bytearray(b'\x01\x02\x03\x04\x05')

bytearray() method returns a bytearray object which is an array of given bytes. It gives a mutable sequence of integers in the range 0 <= x < 256.

Syntax:

bytearray(source, encoding, errors)

Parameters:

source[optional]: Initializes the array of bytes
encoding[optional]: Encoding of the string
errors[optional]: Takes action when encoding fails

Returns: Returns an array of bytes of the given size.

source parameter can be used to initialize the array in few different ways. Let’s discuss each one by one with help of examples.

Code #1: If a string, must provided encoding and errors parameters, bytearray() converts the string to bytes using str.encode()

str = "Geeksforgeeks"

array1 = bytearray(str, 'utf-8')

array2 = bytearray(str, 'utf-16')

print(array1)

print(array2)

Output:

bytearray(b'Geeksforgeeks')
bytearray(b'\xff\xfeG\x00e\x00e\x00k\x00s\x00f\x00o\x00r\x00g\x00e\x00e\x00k\x00s\x00')

 
Code #2: If an integer, creates an array of that size and initialized with null bytes.

size = 3

array1 = bytearray(size)

print(array1)

Output:

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

 
Code #3: If an Object, read-only buffer will be used to initialize the bytes array.

arr1 = bytearray(b"abcd")

for value in arr1:

    print(value)

arr2 = bytearray(b"aaaacccc")

print("Count of c is:", arr2.count(b"c"))

Output:

97
98
99
100
Count of c is: 4

 
Code #4: If an Iterable(range 0<= x < 256), used as the initial contents of an array.

list = [1, 2, 3, 4]

array = bytearray(list)

print(array)

print("Count of bytes:", len(array))

Output:

bytearray(b'\x01\x02\x03\x04')
Count of bytes: 4

Code #5: If No source, an array of size 0 is created.

array = bytearray()

print(array)

Output:

bytearray(b'')

What is a byte array?

A byte array is simply an area of memory containing a group of contiguous (side by side) bytes, such that it makes sense to talk about them in order: the first byte, the second byte etc..

What does byte mean in Python?

In Python, a string object is a series of characters that make a string. In the same manner, a byte object is a sequence of bits/bytes that represent data. Strings are human-readable while bytes are computer-readable.

What is the difference between byte and byte array in Python?

The primary difference is that a bytes object is immutable, meaning that once created, you cannot modify its elements. By contrast, a bytearray object allows you to modify its elements. Both bytes and bytearay provide functions to encode and decode strings.