Python (2.x) list / sublist selection -1 weirdness

Python (2.x) list / sublist selection -1 weirdness

In list[first:last], last is not included.

The 10th element is ls[9], in ls[0:10] there isnt ls[10].

If you want to get a sub list including the last element, you leave blank after colon:

>>> ll=range(10)
>>> ll
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> ll[5:]
[5, 6, 7, 8, 9]
>>> ll[:]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Python (2.x) list / sublist selection -1 weirdness

I get consistent behaviour for both instances:

>>> ls[0:10]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> ls[10:-1]
[10, 11, 12, 13, 14, 15, 16, 17, 18]

Note, though, that tenth element of the list is at index 9, since the list is 0-indexed. That might be where your hang-up is.

In other words, [0:10] doesnt go from index 0-10, it effectively goes from 0 to the tenth element (which gets you indexes 0-9, since the 10 is not inclusive at the end of the slice).

Leave a Reply

Your email address will not be published.