List slices

Cliff Crawford cjc26 at nospam.cornell.edu
Tue Oct 31 11:12:45 EST 2000


* Daniel Klein <DanielK at aracnet.com> menulis:
| Given the list
| 
|     x = ['first','second','third','forth']
| 
| and
| 
|     x[-1]
| 
| returns ['forth'], it seems inconsistent that
| 
|     x[1:-1]
| 
| returns ['second',third'] instead of the expected ['second',third','forth'].
| Can someone provide an explanation for this please?

It actually does make sense. :)  -1 refers to the position in between
the elements 'third' and 'forth':

['first', 'second', 'third', | 'forth']
                             |
                             |
                             -> -1

So x[-1] gets the element after position -1, i.e. 'forth', while x[1:-1]
takes the elements in between positions 1 and -1, 'second' and 'third'.

Another way to remember this is, whenever you see x[:-1], think "chop
off the last element".


-- 
cliff crawford  http://www.people.cornell.edu/pages/cjc26/
                But WHERE are the turtles?



More information about the Python-list mailing list