bytearray() method returns a bytearray object in Python which is an array of given bytes. It gives a mutable sequence of integers in the range 0 <= x < 256.
Syntax of bytearray() Function in Python
Python bytearray() function has the following syntax:
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.
Python bytearray() Function Examples
Let us see a few examples, for a better understanding of the bytearray() function in Python.
bytearray() Function on String
In this example, we are taking a Python String and performing the bytearray() function on it. The bytearray() encodes the string and converts it to byte array object in python using str.encode().
Python3
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')
bytearray() Function on an Integer
In this example, an integer is passed to the bytesrray() function, which creates an array of that size and initialized with null bytes and return byte array object in Python.
Python3
size = 3
array1 = bytearray(size)
print (array1)
|
Output:
bytearray(b'\x00\x00\x00')
bytearray() Function on a byte Object
In this example, we take a byte object. The read-only buffer will be used to initialize the bytes array and return the byte array object in Python.
Python3
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
bytearray() Function on a List of Integers
In this example, We take a Python List of integers which is passed as a parameter to the bytearray() function.
Python3
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
bytearray() Function with no Parameters
If no source is provided to the bytearray() function, an array of size 0 is created and byte array object is returned of that empty array.
Python3
array = bytearray()
print (array)
|
Output:
bytearray(b'')
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
17 Nov, 2023
Like Article
Save Article