4

I have two bytearrays:

ba1 = bytearray(b'abcdefg')
ba2 = bytearray(b'X')

How can I insert ("prepend") ba2 in ba1?

I tried to do:

ba1.insert(0, ba2)

But this doesn't seem to be correct.

Of course I could do following:

ba2.extend(ba1)
ba1 = ba2

But what if ba1 is very big? Would this mean unnecessary coping of the whole ba1? Is this memory-efficient?

How can I prepend a bytearray?

martineau
  • 119,623
  • 25
  • 170
  • 301
user2624744
  • 693
  • 8
  • 23
  • 2
    Have you read this? http://dabeaz.blogspot.se/2010/01/few-useful-bytearray-tricks.html – Henrik Andersson Jan 11 '15 at 05:00
  • 1
    What is the problem with `ba2 + ba1`? – thefourtheye Jan 11 '15 at 05:01
  • possible duplicate of [convert a string of bytes into an int (python)](http://stackoverflow.com/questions/444591/convert-a-string-of-bytes-into-an-int-python) – GLHF Jan 11 '15 at 05:04
  • Since you want to insert stuff at the start of ba1 you can't really get around the need to copy its current contents. OTOH, adding stuff at the end of a bytearray isn't particularly efficient, either: it's similar to concatenating to a string. – PM 2Ring Jan 11 '15 at 05:22

1 Answers1

10

You can do it this way:

ba1 = bytearray(b'abcdefg')
ba2 = bytearray(b'X')

ba1 = ba2 + ba1
print(ba1)  # --> bytearray(b'Xabcdefg')

To make it more obvious that an insert at the beginning is being done, you could use this instead:

ba1[:0] = ba2  # Inserts ba2 into beginning of ba1.

Also note that as a special case where you know ba2 is only one byte long, this would work:

ba1.insert(0, ba2[0])  # Valid only if len(ba2) == 1
martineau
  • 119,623
  • 25
  • 170
  • 301