Python bytearray() Method Tutorial

Python provides the byte data type which can be used for different purposes. The byte array can be defined from scratch or converted from other data types. The bytearray() method is used to convert an array into byte array.

bytearray() Method Syntax

The bytearray() method has the following syntax.

  • SOURCE is the source data that will be converted into the byte array. This can be a string or integer etc. This parameter is provided in most of the cases but optional. If no SOURCE is provided an empty byte array is returned.
  • ENCODING can be used to string SOURCE in order to read with proper encoding. This parameter is optional and if not provided decided automatically.
  • ERROR is the error variable that is used for encoding errors for the string SOURCE. This parameter is optional.

The bytearray() method returns the converted new array.

Convert String Into Byte Array

One of the most used cases for the bytearray() is converting a string into a byte array. The string is a type that consists of single or more characters. So the string can be called a character array. This character array can be converted into the byte array by using the bytearray() method. In the following example, we try to decode provided string as utf-8.

name="My name is John."

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


The output is like below. We can see that the type is bytearray and string is prefixed with letter by in order to express this is a byte type.

bytearray(b'My name is John.')

Create 0 Filled Byte Array with Specified Size

Different variables can be converted into a byte array with the bytearray() method other than string. In the following example, we will convert an integer into a byte array.

size = 10

arr = bytearray(size)


Convert List Into Byte Array

Another popular use case for the byte array is converting a list into a byte array. The list items should be the same type like integer or string.

mylist = [ 1 , 2 , 3 , 4 ]

arr = bytearray(mylist)


Leave a Comment