Python bytearray() function creates a mutable (changeable) sequence of bytes. It’s like a list, but specifically for storing bytes, numerical values between 0 and 255. This is useful when working with raw binary data or manipulating data at a low level.
bytearray()
Syntax
my_bytearray = bytearray(source, encoding, errors)
my_bytearray
: A variable to store the created bytearray objectbytearray()
: The built-in Python function for creating bytearrayssource
(optional): The initial data for the bytearray. Can be a string, an integer specifying the size, or an iterable of integers.encoding
(optional): Ifsource
is a string, specifies how to encode it into bytes.errors
(optional): Ifsource
is a string, specifies how to handle encoding errors.
Example 1: Python bytearray()
my_bytes = bytearray(5) # Create an empty bytearray of size 5
print(my_bytes)
Code Explanation
- Line 1: Creates a bytearray with 5 elements, all initialized to 0.
- Line 2: Prints the bytearray, showing its raw byte values.
Output
bytearray(b’\x00\x00\x00\x00\x00′)
Example 2: Python bytearray()
with String
text = "Hello, world!"
my_bytes = bytearray(text, 'utf-8')
print(my_bytes)
Code Explanation
- Line 1: Assigns a string to the variable
text
. - Line 2: Creates a bytearray from the string, encoding it using UTF-8.
- Line 3: Prints the bytearray, which now contains the byte representation of the string.
Output
bytearray(b’Hello, world!’)
Example 3: Python bytearray()
with Integer Argument
size = 10
my_bytes = bytearray(size)
print(my_bytes)
Code Explanation
- Line 1: Assigns the desired size (10) to the variable
size
. - Line 2: Creates a bytearray with the specified size, all elements initialized to 0.
- Line 3: Prints the bytearray.
Output
bytearray(b’\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00′)
Example 4: Python bytearray()
with List
my_list = [72, 101, 108, 108, 111] # ASCII codes for "Hello"
my_bytes = bytearray(my_list)
print(my_bytes)
Code Explanation
- Line 1: Creates a list containing the ASCII codes for the characters in “Hello”.
- Line 2: Creates a bytearray from the list of integers.
- Line 3: Prints the bytearray, which decodes back to the original string “Hello”.
Output
bytearray(b’Hello’)