printing out elements in list

Tim N. van der Leeuw tim.leeuwvander at nl.unisys.com
Mon May 8 04:53:34 EDT 2006


alist[::2] means taking a slice. You should look up slice-syntax in the
tutorials and reference manual.

in general,

alist[1:5] means: take list elements position 1 up to (excluding) 5.
(List indexing starts at position 0, so the first element in the list
is not included!)
alist[0:5] means: take list elements position 0 up to (excluding) 5; in
other words: the first 5 elements.
A shortcut for this is: alist[:5] -- omitting an index position means a
default of 'start' resp. 'end'.
So to take all elements from the 5th to the end of list, you write:
alist[4:] (remember that indexing starts at position 0, so 0 is your
first element, 4 is your 5th).

To take a slice that is the whole list, write: alist[:]

Slices discussed so far take all elements in the indicated range,
however you can specify a 'step' with your slices. Default step is 1,
but to skip every other element you write:
alist[::2]
Which takes all elements of your list, starting at position 0, adding 2
to the index each step, so next is item 2, then 4, etc, until end of
list.
Now we have all the 'even-numbered' elements in the list, to get the
'odd-numbered elements' write:
alist[1::2]

I hope this helps.


Cheers,

--Tim




More information about the Python-list mailing list