[Tutor] Slicing Tuples

Hugo Arts hugo.yoshi at gmail.com
Sat Dec 11 17:55:54 CET 2010


On Sat, Dec 11, 2010 at 5:25 PM, John Russell <thor at othala.us> wrote:
> Last night I started working through a book (Beginning Python: Using Python
> 2.6 and Python 3.1)  I bought to learn Python, and there is an example in it
> that doesn't make sense to me.
> There is an example on slicing sequences that goes like this:
> slice_me=("The", "next", "time", "we","meet","the","drinks","are","on","me")
> sliced_tuple=slice_me[5:9]
> print(sliced_tuple)
> which, results in
> ('drinks', 'are', 'on', 'me')

That's not really what happens for me, see here:

>>> a = ("The", "next", "time", "we","meet","the","drinks","are","on","me")
>>> a[5:9]
('the', 'drinks', 'are', 'on')
>>> a[6:10]
('drinks', 'are', 'on', 'me')

[6:10] should provide the result you showed. Please make sure to
always copy-paste when quoting code, otherwise inaccuracies like this
will happen.

> there is an example a little further below that shows the same concept, only
> applying it to a string, and, the result is  four characters long, starting
> at the 6th position.
> Now, I understand why they start where they do, because the counting starts
> at 0, so 5 is the 6th element. What I don't understand is why they end where
> they do. By my count, 5 to 9 would be 5 elements, not 4. With the tuple, I
> thought the result was because there wasn't enough elements left, but when I
> changed 5:9 to 5:8, it returned one less result.
> So, my question is this, and I realize that this is *very* basic - what is
> going on with the last element? Why is it returning one less than I think it
> logically should. Am I missing something here? There is not much of an
> explanation in the book, but I would really like to understand what's going
> on here.
>

Very simple, a slice of a[5:9] will return all elements x where 5 <= x
< 9. That's actually 4 elements: 5, 6, 7, and 8. You'll notice that
while the starting number of the slice is included, the end is not.
You might think this strange, but python uses it everywhere. range
does the same:

>>> range(5, 9)
[5, 6, 7, 8]

There are some good reasons to make slices and ranges work like this.
One, you can subtract the numbers in the slice to get the length of
the slice, i.e. len(a_list[x:y]) == y - x.
Two, cutting a list up in two is now very easy and intuitive: l == l[:b] + l[b:]

Hugo


More information about the Tutor mailing list