Python built-in Method - bytearray()
The bytearray()
method is a built-in function in Python that creates a mutable bytearray object from an iterable of integers in the range 0 to 255. A bytearray is similar to a regular Python string, but it can be modified in place by changing the values of its individual elements.
Here is the syntax for bytearray()
method:
bytearray(iterable)
where iterable
is an iterable object containing integers in the range 0 to 255.
Here are some examples of how to use bytearray()
:
# Create a bytearray from a list of integers a = bytearray([72, 101, 108, 108, 111]) print(a) # Output: bytearray(b'Hello') # Create a bytearray from a string b = bytearray('hello', 'utf-8') print(b) # Output: bytearray(b'hello')
In the first example, a list of integers representing the ASCII codes for the characters 'H'
, 'e'
, 'l'
, 'l'
, and 'o'
is passed as an argument to the bytearray()
method, which creates a bytearray object containing those values. The resulting bytearray is printed to the console, and the output shows that it contains the string 'Hello'
.
In the second example, a string 'hello'
is passed as an argument to the bytearray()
method, along with the 'utf-8'
encoding parameter. The utf-8
encoding is used to convert the string to a sequence of bytes, which is then used to create the bytearray object. The resulting bytearray is printed to the console, and the output shows that it contains the string 'hello'
.
The bytearray()
method can be useful when you need to work with byte data, such as when reading and writing binary files or communicating with hardware that uses byte-oriented protocols. Since bytearray objects are mutable, they can be modified in place, which can be useful for optimizing performance or reducing memory usage in certain applications.