Tutorial Study Image

Python bytearray()

As the name indicates bytearray is an object, which is an array of bytes. This array of bytes has got tremendous applications mostly in data manipulation. For example, while encoding, compressing, and mapping data byte arrays are used.

In the python bytearray() function takes an object as input and can produce the corresponding byte array which is mutable.


bytearray(a, encoding, error) #where a can be an object or an integer 

bytearray() Parameters

Takes 3 parameters where the first parameter can be an object and if the object is a string the encoding format to be specified as the second parameter.

Parameter Description Required / Optional
Value The value can be an integer, string, or an iterable Optional

Encoding
If the string is passed as a parameter, the string encoding to be specified If the first parameter is a string then required
Error To specify what to be done on error Optional

bytearray() Return Value

The return value will be different based on the type of the parameter passed as input.

Input Output
Integer A byte array of the specified size initialized
String as first parameter and encoding as the second parameter The string encoded to bytes
Iterable Byte array as the same size as the iterable
No parameter Creates a byte array with no elements

bytearray() Examples

Passing an integer as a parameter

byte_array = bytearray(3) 
print(byte_array)

Output:

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

Passing a string as a parameter

string = "Happy!" print(bytearray(string, 'utf-8'))

Output:

bytearray(b'Happy!')

Passing an iterable as parameter

keys = {1 : ‘a’,2:’b’} 
print(bytearray(keys))

Output:

bytearray(b'\x01\x02') When dictionary is passed its keys will be converted to bytearray