Python bytearray Function with Examples

The bytearray function in Python generates a bytearray object, which can either transform various objects into bytearray instances or produce an empty bytearray of a designated size.

Python bytearray Function Syntax

It has the following syntax:

Example

bytearray(x, encoding, error)

Parameters

  • x (optional): It is the source that initializes the array of bytes.
  • encoding (optional): It is an encoding of the string.
  • error (optional): It takes action when the encoding fails.
  • Return

It returns an array of bytes.

Different Examples for Python bytearray Function

In this section, we will explore various instances of the Python bytearray function.

Python bytearray Function Example 1

The following example demonstrates how to represent a string as an array of bytes:

Example

string = "Python is programming language."

# string with encoding 'utf-8'

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

print(arr)

Output:

Output

bytearray(b'Python is programming language.')

Clarification: In the example presented above, we take a variable holding a string value and transform it into a bytearray object.

Python bytearray Function Example 2

The following example illustrates an array of bytes corresponding to a specified integer size:

Example

size = 5

arr = bytearray(size)

print(arr)

Output:

Output

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

Python bytearray Function Example 3

The following illustration demonstrates a byte array derived from an iterable collection:

Example

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

arr = bytearray(rList)

print(arr)

Output:

Output

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

Input Required

This code uses input(). Please provide values below: