Skip to content

Python bytearray() Function

How to create and modify mutable byte sequences in Python using the bytearray() function, including syntax, parameters, and practical examples with strings, integers, and error handling.

The bytearray() function returns a mutable bytearray object.

It can convert objects into bytearray objects, or create empty bytearray object of the specified size.

Syntax

bytearray(x, encoding, error)

bytearray() Parameters

Python bytearray() function parameters:

Parameter Condition Description
x Optional A source to use when creating the bytearray object.
If it is an integer, an empty bytearray object of the specified size will be created.
If it is a String, make sure you specify the encoding of the source.
encoding Optional The encoding of the string like ascii, utf-8, windows-1250, windows-1252, etc.
error Optional Specifies what to do if the encoding fails (strict, replace, ignore, backslashreplace)

bytearray() Return Value

Python bytearray() method returns an array of bytes of the given size and initialization values.

Examples

Example 1: Basic examples

The following example shows various ways to create bytearray objects:

print(bytearray(b''))       # Output: bytearray(b'')
print(bytearray(4))         # Output: bytearray(b'\x00\x00\x00\x00')
print(bytearray([0,1,2]))   # Output: bytearray(b'\x00\x01\x02')

output

bytearray(b'')
bytearray(b'\x00\x00\x00\x00')
bytearray(b'\x00\x01\x02')

Example 2: array of bytes from a string

Let's convert a string into a bytearray while specifying the encoding.

string = "This is Tutorial Reference!"

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

output

bytearray(b'This is Tutorial Reference!')

Example 3: array of bytes of given integer size

Let's create a bytearray of a specific size using an integer value:

size = 5

arr = bytearray(size)
print(arr)

output

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

Example 4: array of bytes from an iterable list

Let's convert an iterable list of integers into a bytearray:

rList = [1, 2, 3, 4, 5]

arr = bytearray(rList)
print(arr)

output

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

Examples using also encoding and error parameters

See some examples of what happens with encoding as ascii and the various errors

Example:

print(bytearray(u'źdźbło', 'ascii', 'strict'))
Traceback (most recent call last):
  File "main.py", line 1, in <module>
    print(bytearray(u'źdźbło', 'ascii', 'strict'))
UnicodeEncodeError: 'ascii' codec can't encode character '\u017a' in position 0: ordinal not in range(128)

Example:

print(bytearray(u'źdźbło', 'ascii', 'ignore'))
bytearray(b'dbo')

Example:

print(bytearray(u'źdźbło', 'ascii', 'replace'))
bytearray(b'?d?b?o')

Example:

print(bytearray(u'źdźbło', 'ascii', 'xmlcharrefreplace'))
bytearray(b'&#378;d&#378;b&#322;o')

Example:

print(bytearray(u'źdźbło', 'ascii', 'backslashreplace'))
bytearray(b'\\u017ad\\u017ab\\u0142o')
Navigation