[Tutor] s[len(s):len(s)] = [x] ??

Alan Gauld alan.gauld at btinternet.com
Tue Jul 1 01:09:33 CEST 2008


"Jerry Hill" <malaclypse2 at gmail.com> wrote

> You can do it with slice assignment too:
>>>> a = [1, 2, 3, 4]
>>>> a[1:3] = [[7, 8]]
>>>> a
> [1, [7, 8], 4]
>
> Now, which way is better?  The answer depends on context.

> If, conceptually, you are removing two elements from a list, then
> adding a new element which is itself a list, then doing it with 
> remove
> and insert is probably best.

Even in that case I'd replace themultiple removes with a slice:

>>> L = [1,2,3,4]
>>> L[1:3] = []
>>> L.insert(1,[7,8])
>>> L
[1, [7, 8], 4]

HTH,

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld 




More information about the Tutor mailing list