What is the difference between bytearray
and for example, a list
or tuple
?
As the name suggests, bytearray
must be an array
that carries byte
objects.
In python, it seems that bytes
and str
are treated equally
>>> bytes
<type 'str'>
So, what is the difference?
Also, if you print a bytearray
, the result is pretty weird
>>> v = bytearray([200, 201])
>>> print v
ÈÉ
It seems that it transforms the integer in chr(integer)
, is that right? What is the use of a bytearray
then?
You are correct in some way: In Python 2, bytes
is synonymous with the str
type. This is because originally, there was no bytes
object, there was only str
and unicode
(the latter being for unicode string, i.e. having multi-byte capabilities). When Python 3 came, they changed the whole string things and made unicode the default Python 3 str
type, and they added bytes
as the type for raw byte sequences (making it equivalent to Python 2’s str
object).
So while in Python 3 you differ between str
and bytes
, the corresponding types in Python 2 are unicode
and str
.
Now what makes the bytearray
type interesting is that it’s mutable. All string and byte sequences above are immutable, so with every change, you are creating a new object. But you can modify bytearray
objects, making them interesting for various purposes where you need to modify individual bytes in a sequence.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With