[Tutor] list.append(x) but at a specific 'i'

Steven D'Aprano steve at pearwood.info
Wed Sep 22 21:47:45 CEST 2010


On Wed, 22 Sep 2010 08:30:09 am Norman Khine wrote:

> hello, how do i extend a python list but from a given [i], 

Do you mean to modify the list in place, like append() and extend() do, 
or do you mean to create a new list, like + does?


> for example: 
> >>> a = ['a', 'b', 'e']
> >>> b = ['c', 'd']
> >>>
> >>> a + b
>
> ['a', 'b', 'e', 'c', 'd']
>
>
> but i want to put the items of 'b' at [-2] for example.

When you ask a question, it usually helps to show the output you *want*, 
not the output you *don't want*, rather than to make assumptions about 
what other people will understand.

When you say that you want the items of b *at* -2, taken literally that 
could mean:

>>> a = ['a', 'b', 'e']
>>> b = ['c', 'd']
>>> a.insert(-2+1, b)
>>> print(a)
['a', 'b', ['c', 'd'], 'e']

Note that the items of b are kept as a single item, at the position you 
ask for, and the index you pass to insert() is one beyond when you want 
them to appear.

To create a new list, instead of insert() use slicing:

>>> a[:-2+1] + [b] + a[-2+1:]
['a', 'b', ['c', 'd'], 'e']


If you want the items of b to *start* at -2, since there are exactly two 
items, extend() will do the job for in-place modification, otherwise +. 
But you already know that, because that was your example.

If you want the items of b to *end* at -2, so that you get 
['a', 'b', 'c', 'd', 'e'] then you could use repeated insertions:

for c in b:
    a.insert(-2, c)

but that will likely be slow for large lists. Better to use slicing. To 
create a new list is just like the above, except you don't create a 
temporary list-of-b first:

>>> a[:-2+1] + b + a[-2+1:]
['a', 'b', 'c', 'd', 'e']


To do it in place, assign to a slice:

>>> a[-2:-2] = b
>>> print(a)
['a', 'c', 'd', 'b', 'e']



-- 
Steven D'Aprano


More information about the Tutor mailing list