bytearray
is a sequence-type, and it supports slice-based operations. The "insert at position i
" idiom with slices goes like this x[i:i] = <a compatible sequence>
. So, for the fist position:
>>> a
bytearray(b'\x00\x00\x00\x01')
>>> b
bytearray(b'\x00\x00\x00\x02')
>>> a[0:0] = b
>>> a
bytearray(b'\x00\x00\x00\x02\x00\x00\x00\x01')
For the third position:
>>> a
bytearray(b'\x00\x00\x00\x01')
>>> b
bytearray(b'\x00\x00\x00\x02')
>>> a[2:2] = b
>>> a
bytearray(b'\x00\x00\x00\x00\x00\x02\x00\x01')
Note, this isn't equivalent to .insert
, because for sequences, .insert
inserts the entire object as the ith element. So, consider the following simple example with lists:
>>> y = ['a','b']
>>> x.insert(0, y)
>>>
>>> x
[['a', 'b'], 1, 2, 3]
What you really wanted was:
>>> x
[1, 2, 3]
>>> y
['a', 'b']
>>> x[0:0] = y
>>> x
['a', 'b', 1, 2, 3]