Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prepending bytearray: TypeError: an integer is required

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?

like image 261
user2624744 Avatar asked Oct 27 '25 10:10

user2624744


1 Answers

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
like image 183
martineau Avatar answered Oct 30 '25 00:10

martineau



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!