In other words, I want to accomplish something like the following:
a = [1, 2, 3, 7, 8]
b = [4, 5, 6]
# some magic here to insert list b into list a at index 3 so that
a = [1, 2, 3, 4, 5, 6, 7, 8]
In other words, I want to accomplish something like the following:
a = [1, 2, 3, 7, 8]
b = [4, 5, 6]
# some magic here to insert list b into list a at index 3 so that
a = [1, 2, 3, 4, 5, 6, 7, 8]
You can assign to a slice of list a
like so:
>>> a = [1, 2, 3, 7, 8]
>>> b = [4, 5, 6]
>>> a[3:3] = b
>>> a
[1, 2, 3, 4, 5, 6, 7, 8]
>>>
The [3:3]
may look weird, but it is necessary to have the items in list b
be inserted into list a
correctly. Otherwise, if we were to assign to an index of a
, list b
itself would be inserted:
>>> a = [1, 2, 3, 7, 8]
>>> b = [4, 5, 6]
>>> a[3] = b
>>> a
[1, 2, 3, [4, 5, 6], 8]
>>>
I tried to find a docs link which explicitly mentions this behavior, but was unsuccessful (please feel free to add one if you can find it). So, I'll just say that doing a[3:3] = b
tells Python to take the items in list b
and place them in the section of list a
represented by [3:3]
. Moreover, Python will extend list a
as necessary to accommodate this operation.
In short, this is just yet another awesome feature of Python. :)
Try using the sort method as follows:
>>> a = [1,2,3,7,8]
>>> b = [4,5,6]
>>> a = sorted(a+b)
>>> a
[1, 2, 3, 4, 5, 6, 7, 8]