In this lesson, you’ll explore bytearray objects. bytearray objects are very similar to bytes objects, despite these differences:
- There is no dedicated syntax for defining a
bytearrayliteral. - A bytearray is always created using the
bytearray()built-in function. bytearrayobjects are mutable.
Here’s an example:
>>> ba = bytearray('spam.egg.bacon', 'utf8')
>>> ba
bytearray(b'spam.egg.bacon')
>>> type(ba)
<class 'bytearray'>
>>> ba2 = bytearray(6)
>>> ba2
bytearray(b'\x00\x00\x00\x00\x00\x00')
>>> ba3 = bytearray([97, 98, 99, 100, 101])
>>> ba3
bytearray(b'abcde')
>>> ba3[4] = 0xee
>>> ba3
bytearray(b'abcd\xee')
>>> ba3[:3] = b'egg'
>>> ba3
bytearray(b'eggd\xee')
>>> ba4 = bytearray(b'spam')
>>> ba4
bytearray(b'spam')

Adam Masiarek on June 19, 2021