pythonarrayslistpython-bytearray

How can I append multiple copies of a value to a Python bytearray?


If I have a Python list (data) and two integers (i and count), I can easily append count copies of i to data:

>>> data = [0]
>>> i, count = 1, 4
>>> data += [i] * count
>>> data
[0, 1, 1, 1, 1]

How can I do the same if data is a bytearray? Is it necessary to create a list first, e.g. data += bytearray([i] * count)?


Solution

  • Is it necessary to create a list first, e.g. data += bytearray([i] * count)?

    That is indeed one way to do it. You can do the multiply operation on the byte array (as opposed to the list), which is slightly more memory-efficient and much faster for large values of count*:

    >>> data = bytearray([0])
    >>> i, count = 1, 4
    >>> data += bytearray((i,)) * count
    >>> data
    bytearray(b'\x00\x01\x01\x01\x01')
    

    * source: Works on my machine; YMMV! Tried with a count of 4000000000, which went out of memory when multiplying the list, but not when multiplying the bytearray. Smaller values of count (600000000) use more than 8 times as much memory when multiplying a list than when multiplying a bytearray.