Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between bytearray and list

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?

like image 433
rafaelc Avatar asked May 09 '15 22:05

rafaelc


1 Answers

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.

like image 173
poke Avatar answered Sep 22 '22 00:09

poke