[Tutor] Explanation of Lists data Type
alan.gauld at freenet.co.uk
Wed Apr 12 19:17:17 CEST 2006
> 8.7 List slices
You might find it worth going through the official tutor section
on slicing, it explains the various forms quite well.
>>> list[:4] --> Does this mean its list[0:4]
Sort of, it means from *the beginning* to 4.
>>> list[3:] --> Does this mean its list[3:0]
No it means from 3 to *the end*
>>> list[:] --> Does this mean its list[0:0]
No, it means from *the beginning* to *the end*
These are all just shortcut conventions that you need to learn.
Another one that can be confusing is negative slices:
means from the -3 position(ie 3 from the end) to the end
means from the 3rd position to the -3 position
I find it helps to thingk of the collection organised as a ring
with the counter sitting between the items. Thus zero sits
between the first and last items. Unfortunately this breaks down if you do
which is an error but is not reported as such, rathger it returns
an empty list!
Basically, play with them a lot and you will get used to their
little oddities, the huge benefits outweigh the occasional confusion.
Author of the learn to program web tutor
More information about the Tutor