Table of Contents

6. Bytearray

Bytearray is a mutable implementation of an array of bytes. Therefore, appending data to a bytearray object is much faster than to a bytes object because in this last case, every append implies to create (and destroy the previous) new bytes object.


In [ ]:
%%timeit x = b''
x += b'x'

In [ ]:
%%timeit x = bytearray()
x.extend(b'x')

In [ ]:
# Array of bytes = 0
x = bytearray(10)

In [ ]:
x

In [ ]:
len(x)

In [ ]:
for i in range(len(x)):
    x[i] += 1

In [ ]:
x

In [ ]:
# A byte in Python is a 0 <= value <= 255.
x[1] = -1

In [ ]:
# A bytearray can be created from a list
x = bytearray([1,2,3])
x

In [ ]:
import sys
x = bytearray(sys.stdin.read(5).encode())
x