9

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]
MrDuk
  • 16,578
  • 18
  • 74
  • 133

2 Answers2

15

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. :)

Community
  • 1
  • 1
  • 3
    Would it be much to ask "why" this works? I mean, intuitively, if we take an array metaphor, this shouldn't work, because there is not "space" between one element and another to add N more elements. Obviously, python implements lists in a way that makes this possible, but I ask: "is there something in the spec that allows us to _predict_ that this should work?" (otherwise it would be a hack). +1 ! – heltonbiker Oct 28 '14 at 15:56
  • @heltonbiker - Let me go dig through the docs to see if this behavior is documented. If not, I'll try to explain it myself. –  Oct 28 '14 at 16:03
  • 1
    `a[3:3]` represents the part of `a` comprised between `3` and `3` (i.e. `[]`, but other indexes would give different sublists). It is a sublist of `a`. `a[3:3] = b` assigns the content of `b` to that sublist, regardless of their respective sizes. – njzk2 Oct 28 '14 at 16:06
  • @heltonbiker - Eh, I couldn't find a docs link. It looks like this is just a neat little feature (hack?) of Python. :) –  Oct 28 '14 at 16:33
  • 4
    This is mentioned by the docs in the tutorial, see [here](https://docs.python.org/2/tutorial/introduction.html#lists)). They don't show exactly that `a[3:3] = b` will work however they show `a[2:5] = []` which modifies the length of the list by removing elements in the middle, so I'd expect to be able to insert them too. And they *do* explicitly say that modifying the size is allowed (and they never mention that you can do that only at the end, and in fact examples are assigning in the middle). – Bakuriu Oct 28 '14 at 17:26
3

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]