Methods and Functions

Python bytearray()

The python bytearray function is used to return a bytearray object. It can either convert objects to bytearray objects or construct an empty bytearray object of the desired size.

python bytearray

Source

Syntax:

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

bytearray() Parameters

bytearray() takes three optional parameters:

  1. source (Optional) – source initializes the array of bytes

Depending on the type of source, the bytearray() function follows some specific rules.

  • If there is no parameter, an empty byte array is returned.
  • If the source is a string, the encoding argument must be used.
  • The array will have the same size as the source and will be initialized with null bytes if the source is an integer.
  • If the source is a buffer interface object, the bytes array will be initialized with a read-only buffer from the object.
  • If the source is an iterable object, the elements must all be integers in the range 0 to 256.
  1. encoding (Optional) – If the source is a string, the string’s encoding is returned.
  2. errors (Optional) – if the source is a string when encoding fails, it takes action.

Return value from bytearray()

The bytearray() function returns a byte array with the specified size and initialization settings.

Example 1: Array of bytes from a string

                    

string = "Python is my favorite subject."



# string with encoding 'utf-8'

arr = bytearray(string, 'utf-8')

print(arr)

Output:

bytearray(b'Python is my favorite subject.')

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')

What is a Bytearray in Python?

The bytearray() method returns a bytearray object, which is an array of bytes. It returns a mutable series of integers between 0 and 256. The source parameter of the ByteArray is used to initialize the array. Such as:

Method 1:

Bytearray() transforms a string to bytes using str.encode() if the encoding and errors parameters are given

Source Code:

                    

str = "Geeksforgeeks"

  

# Using Unicode 8 and 16 to 

# encode the string

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')

Method 2:

If the value is an integer, it produces an array of that size with null bytes.

Source Code:

                    

size = 3

  

# will make an array of the #specified size and fill it with null 

# bytes

array1 = bytearray(size)

  

print(array1)



Output:

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

 

Method 3:

The read-only buffer will be utilized to initialize the bytes array if it is an Object.

Source Code

                    

# Bytearray is created from a byte literal

arr1 = bytearray(b"abcd")

  

#the value being iterated

for value in arr1:

    print(value)

      

# Create a bytearray object

arr2 = bytearray(b"aaaacccc")

  

# count bytes from the buffer

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



Output:

97

98

99

100

Count of c is: 4

 

Method 4: 

If an Iterable(range 0=x 256) is used as the array’s initial contents

Source Code

                    

# simple list of integers

list = [1, 2, 3, 4]

  

# iterable as source

array = bytearray(list)

  

print(array)

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



Output:

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

Count of bytes: 4

 

Method 5:

If there is no source, a zero-sized array is constructed.

Source Code

                    

# There will be a size 0 array formed.

  

# iterable as source

array = bytearray()

  

print(array)



Output:

bytearray(b'')

What is the Difference Between Bytes and bytearray in Python?

The bytes and bytearray classes both feature arrays of bytes with values ranging from 0 to 255 for each byte. The main difference is that a bytes object is immutable, which means that once formed, its elements cannot be changed. A bytearray object, on the other hand, allows you to change its elements.

Program to append bytes and bytearrays

The ‘+ operator’ can be used to catenate bytes and bytearray objects. Note that the catenated result inherits the first argument’s type, so a+b produces bytes object, while b+a produces a bytearray.

Source Code

                    

>>> a = bytes(3)

>>> a

b'\x00\x00\x00'



>>> b = bytearray(4)

>>> b

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



>>> a+b

b'\x00\x00\x00\x00\x00\x00\x00'



>>> b+a

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

What is a Bytearray?

A byte array is simply a collection of bytes. The bytearray() method returns a bytearray object, which is an array of the specified bytes. The bytearray class is a mutable array of numbers ranging from 0 to 256.

Example to convert integer to bytearrays

                    

>>> a = bytes(3)

>>> a

b'\x00\x00\x00'



>>> b = bytearray(4)

>>> b

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



>>> a+b

b'\x00\x00\x00\x00\x00\x00\x00'



>>> b+a

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

Is Bytearray mutable in python?

Yes, the Bytearray function in Python is mutable. This indicates that the elements of the function can be easily altered. 

For example:

                    

b = bytearray('abc', 'UTF-8') 



print(b) 



b[1] = 65 # mutable 



print(b)



Output:



bytearray(b'abc')

bytearray(b'aAc')

Share with friends

Customize your course in 30 seconds

Which class are you in?
5th
6th
7th
8th
9th
10th
11th
12th
Get ready for all-new Live Classes!
Now learn Live with India's best teachers. Join courses with the best schedule and enjoy fun and interactive classes.
tutor
tutor
Ashhar Firdausi
IIT Roorkee
Biology
tutor
tutor
Dr. Nazma Shaik
VTU
Chemistry
tutor
tutor
Gaurav Tiwari
APJAKTU
Physics
Get Started

Leave a Reply

Your email address will not be published. Required fields are marked *

Download the App

Watch lectures, practise questions and take tests on the go.

Customize your course in 30 seconds

No thanks.