Python bytearray() Function – Tutorial with Examples

The bytearray() function in Python is a built-in function that returns a new array of bytes. It is a mutable sequence of integers in the range 0 <= x < 256. The function can be used to convert data from different types into a bytearray object.

Basic Information

  • The bytearray() function is a part of the built-in functions in Python and does not require any imports.
  • The function can take different arguments to create a bytearray object such as a string, an integer array, a bytes object, and others.
  • The bytearray object is mutable, which means the elements in the array can be modified after the object has been created.

Syntax

bytearray([source[, encoding[, errors]]])

where source is the data source to be converted into a bytearray object, encoding is the encoding type used to convert the source data into bytes (UTF-8 by default), and errors is the error handling scheme (strict by default).

Return Value

The bytearray() function returns a bytearray object that contains the byte representation of the data passed as an argument.

Examples

Example 1: Creating a bytearray from a string

# Create a bytearray from a string
str = "Hello, World!"
bytearr = bytearray(str, 'utf-8')
print("Bytearray:", bytearr)
print("Type:", type(bytearr))

# Output:
# Bytearray: b'Hello, World!'
Type: <class 'bytearray'>

Example 2: Creating a bytearray from an integer array

# Create a bytearray from an integer array
int_array = [10, 20, 30, 40, 50]
bytearr = bytearray(int_array)
print("Bytearray:", bytearr)
print("Type:", type(bytearr))

# Output:
# Bytearray: b'\n\x14\x1e('
# Type: <class 'bytearray'>

Example 3: Creating a bytearray from a bytes object

# Create a bytearray from a bytes object
byts = b'Hello, World!'
bytearr = bytearray(byts)
print("Bytearray:", bytearr)
print("Type:", type(bytearr))

# Output:
# Bytearray: b'Hello, World!'
# Type: <class 'bytearray'>

Example 4: Modifying elements in a bytearray

# Modifying elements in a bytearray
bytearr = bytearray(b'Hello, World!')
bytearr[0] = 72
print("Bytearray after modification:", bytearr)
# Output:
# Bytearray after modification: b'H ello, World!'

Conclusion

In this article, we learned about the bytearray() function in Python and its different uses. We saw how to create a bytearray object from different data sources such as strings, integer arrays, and bytes objects. The bytearray object is mutable, making it useful for cases where the data needs to be changed after creation. Try using the bytearray() function in your projects and see how it can be useful in solving different problems.

Leave a Reply

Your email address will not be published. Required fields are marked *