Return a new array of bytes that is mutable.
The bytearray class returns a new array of bytes. The bytearray type is a mutable sequence of integers in the range 0 to 255. It has most of the usual methods of mutable sequences as well as most methods of the bytes type.
The constructor can be called with several types of arguments. With a string and encoding, it converts the string to bytes. With an integer, it creates a zero-filled bytearray of that size. With an iterable of integers, it creates a bytearray from those values.
Bytearray objects are useful when you need to modify byte data in place, such as when implementing network protocols, working with binary file formats, or performing in-place byte manipulations that would be inefficient with immutable bytes objects.
| Name | Description | Optional |
|---|---|---|
source |
The source to initialize the bytearray from. | Yes |
encoding |
The encoding to use if source is a string. | Yes |
errors |
The error handling scheme to use for encoding errors. | Yes |
bytearray(5) # Returns bytearray(b'\x00\x00\x00\x00\x00')
bytearray('hello', 'utf-8') # Returns bytearray(b'hello')