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

Norman Khine norman at khine.net
Fri Sep 24 19:58:44 CEST 2010


On Wed, Sep 22, 2010 at 9:47 PM, Steven D'Aprano <steve at pearwood.info> wrote:
> 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']

thanks for all the replies, and the detailed information
>
>
>
> --
> Steven D'Aprano
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>



-- 
˙uʍop ǝpısdn p,uɹnʇ pןɹoʍ ǝɥʇ ǝǝs noʎ 'ʇuǝɯɐן sǝɯıʇ ǝɥʇ puɐ 'ʇuǝʇuoɔ
ǝq s,ʇǝן ʇǝʎ
%>>> "".join( [ {'*':'@','^':'.'}.get(c,None) or
chr(97+(ord(c)-83)%26) for c in ",adym,*)&uzq^zqf" ] )


More information about the Tutor mailing list