6

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?

rafaelc
  • 57,686
  • 15
  • 58
  • 82
  • See here https://stackoverflow.com/questions/9099145/where-are-python-bytearrays-used – dhke May 09 '15 at 22:10

1 Answers1

15

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.

poke
  • 369,085
  • 72
  • 557
  • 602
  • 2
    The other thing that makes `bytearray` interesting (compared to Python's `str`, not so much compared to Python 3's `bytes`) is that it's a bit ambiguous what it's an array of. In Python 2, sometimes bytes are characters, and sometimes they're small numbers. if ` = bytearray([97,98,99])`, `repr(b)` gives you `bytearray(b'abc')`. But `b[0]` gives you `97`. This can be confusing if you're used to `str` hiding that from you and forcing you to call `ord` and `chr` (`'abc'[0]` is `'a'`, not 97). – abarnert May 09 '15 at 22:25