Python bytearray
bytearray is a mutable sequence of integers in the range 0-255. It is useful when you need a modifiable sequence of bytes.
Creating bytearrays
Create a bytearray from size, from an iterable of integers, or by decoding bytes.
Example
Initialize from values and modify items (mutable):
b = bytearray([65, 66, 67])
print(b) # bytearray(b'ABC')
b[0] = 97 # change 'A' to 'a'
print(b) # bytearray(b'aBC')
Try it Yourself »
Common operations
- Supports indexing, slicing, appending, extending, and methods like
.find()and.replace(). - Can be converted to
byteswithbytes(barr).
Example
Append and decode:
b = bytearray(b"Hello ")
b.extend(b"World")
print(b)
print(b.decode("utf-8"))
See also
Reference: bytearray()