Python bytearray()

In this article, we will learn the usage and syntax of the bytearray() method in Python with examples.

A bytearray is similar to a string, with the only difference being that whereas a string cannot be changed once declared, bytearrays can be.  Therefore, bytearrays provide more flexibility than a string as it allows manipulation of its elements as either number (in the range of 0-256)  or as one-char strings.

Using bytearray() in Python – Syntax

To create a bytearray in Python, we use the bytearray() method in Python.

Input data type: string/integer/iterable
Output data type: array of bytes

The bytearray() method has no essential parameters. Calling the method without any arguments returns an array of size 0. 

 

#creating a bytearray
array1 = bytearray()
print(array1)

 

Output:
bytearray(b'')

 

The optional ‘source’ parameter can be provided to the method. Depending on the type of ‘source’ parameter, the syntax undergoes some changes.

 

If ‘source’ is a string: bytearray()

The method converts the string into an array of bytes.

Additional parameters required: 

  • Encoding[Essential] – This parameter defines the encoding of the string provided as the source. It can have values like ‘utf-8’, ‘ascii’, etc.
  • Errors[Optional] – This parameter says what should be done should the code run into an error, such as an encoding conversion failure. It can have values like ‘strict’, ‘replace’, etc.

 

#creating a bytearray with parameter 'source' as a string
text = "Bytearray in Python"
array1 = bytearray(text, 'utf-8', 'ignore')
print(array1)

Output:

bytearray(b'Bytearray in Python')

 

If ‘source’ is an integer

The method converts the string into an array of null bytes, and does not require any additional parameters.

 

#creating a bytearray with parameter 'source' as an int
array1 = bytearray(10) 
print(array1)

Output :

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

 

If ‘source’ is an iterable (eg. List/Tuple)

If the ‘source’ is iterable, this method creates an array of size equal to the iterable count.
This is initialized to the elements in the iterable.

 

#creating a bytearray with parameter 'source' as an iterabe
ar1 = (1, 2, 3, 4)
ar2 = [5, 6, 7, 8]
array1 = bytearray(ar1) 
array2 = bytearray(ar2) 
print(array1) 
print(array2)

Output:

bytearray(b'\x01\x02\x03\x04')
bytearray(b'\x05\x06\x07\x08')

Also read:

One response to “Python bytearray()”

Leave a Reply