[Tutor] Insert elements in a lis
alan.gauld at blueyonder.co.uk
Tue Aug 10 23:09:07 CEST 2004
> Is it possible to insert elements in a list in an easy way?
>>> print [1,3,5].insert(1,2)
Is that easy enough? :-)
You can also insert sublists etc too. The official tutor covers
all this stuff quite well.
There is a trick using slices:
>>> L = [1,3,5]
>>> L[2:2] = [4, 4.5] # insert a sequence
>>> print L
[1, 3, 4, 4.5, 5]
The trick is to remember that slices effectively point
*between* the members so [2:2] points to the region from
"just before 2" to "just before 2" - ie between 1 and 2...
Think about it :-)
Author of the Learn to Program web tutor
More information about the Tutor