bytearray() Builtin Function

Python – bytearray()

Python bytearray() builtin function returns an empty byte array when no arguments are passed, byte array of specific size if size is specified, or a byte array created from the given string object and encoding.

Syntax

The syntax of bytearray() function is

bytearray(x, encoding, error)

where

  • x source for byte array
    • if x is integer, then bytearray() returns a byte array of this size.
    • if x is string, then bytearray() returns byte array created using the characters in the string, and specified encoding.
  • encoding is the encoding to be used, if x is a string.
  • error is the action to be performed if encoding fails.

Examples

bytearray() with integer as argument

In the following program, we pass a positive integer to bytearray() function, to create an array of the specified size.

Python Program

x = 5
output = bytearray(x)
print(f'x            : {x}')
print(f'bytearray(x) : {output}')
Run

Output

x            : 5
bytearray(x) : bytearray(b'\x00\x00\x00\x00\x00')

bytearray() with string as argument

In the following program, we pass a string value to bytearray() function, to create byte array from the characters in the string. We specify the encoding 'utf-8'.

Python Program

x = "apple"
output = bytearray(x, 'utf-8')
print(f'x            : {x}')
print(f'bytearray(x) : {output}')
Run

Output

x            : apple
bytearray(x) : bytearray(b'apple')

Summary

In this tutorial of Python Examples, we learned the syntax of bytearray() function, and how to create a byte array of specific size, or byte array initialised using string argument, with examples.