What is the difference between array.array('B') and bytearray?
from array import array
a = array('B', 'abc')
b = bytearray('abc')
a[0] = 100
b[0] = 'd'
print a
print b
Are there any memory or speed differences? What is the preferred use case of each one?
bytearrayis the successor of Python 2.x’sstringtype. It’s basically the built-in byte array type. Unlike the originalstringtype, it’s mutable.The
arraymodule, on the other hand, was created to create binary data structures to communicate with the outside world (for example, to read/write binary file formats).Unlike
bytearray, it supports all kinds of array elements. It’s flexible.So if you just need an array of bytes,
bytearrayshould work fine. If you need flexible formats (say when the element type of the array needs to be determined at runtime),array.arrayis your friend.Without looking at the code, my guess would be that
bytearrayis probably faster since it doesn’t have to consider different element types. But it’s possible thatarray('B')returns abytearray.