[newbie] troubles with tuples

Denis McMahon denismfmcmahon at gmail.com
Tue Feb 4 01:50:44 CET 2014


On Mon, 03 Feb 2014 08:50:31 -0800, Jean Dupont wrote:

> I'm looking at the way to address tuples e.g.
> tup2 = (1, 2, 3, 4, 5, 6, 7 );
> 
> As I found out indices start with 0 in Python, so tup2[0] gives me 1,
> the first element in the tuple as expected tup2[1] gives me 2, the
> second element in the tuple as expected now here comes what surprises
> me:
> tup2[0:1] does not give me the expected (1,2) but (2,)
> 
> what is the reason for this and how then should one get the first and
> the second element of a tuple? Or the 3rd until the 5th?
> 
> thanks in advance and kind regards,
> 
> jean

>>> tup = (0,1,2,3,4,5,6,7)
>>> tup[0:1]
(0,)
>>> tup[1:2]
(1,)
>>> tup[2:3]
(2,)
>>> tup[0:2]
(0, 1)
>>> tup[2:5]
(2, 3, 4)

This is as I'd expect, as the notation [0:1] means:

starting from the 0th element, up to and including the element preceding 
the first element

Or [m:n] means starting from the mth element, everything up to and 
including the element preceding the nth element

Are you sure you got (2,) for [0:1] and not for [2:3]? Are you sure your 
initial tuple is what you thought it was?

-- 
Denis McMahon, denismfmcmahon at gmail.com



More information about the Python-list mailing list