[Tutor] more on index handling
Alan Gauld
alan.gauld at blueyonder.co.uk
Tue Apr 13 18:44:17 EDT 2004
> Question : why does python exclude the last index of a slice ? Below
what I
> mean :
> ************
> >>> l=[1,2,3,4,5]
> >>> l[1:3]
> [2, 3]
> ************
> I would "naturally" expect that l[1:3] returns [1,2,3], but as i
know that
> the indexes are 0-based I expect python to return [2,3,4].
Slices are different :-)
They work like a knife being inserted before the items you specify.
So thinking of
[1,2,3,4,5]
Inset the knife before item 1 and item 3 (at the comma if you like)
and you get [2,3]...
Why? Dunno, but it's consistent with the range function
range(1,3)
returns [1,2] not [1,2,3]
and slicing [0,1,2,3] with [1:3} returns [1,2] the same as range.
So you can think of range as a type of slicing function...
No it's not very convincing is it?! :-)
Alan G.
More information about the Tutor
mailing list