Python list / sublist selection -1 weirdness


Question

So I've been playing around with python and noticed something that seems a bit odd. The semantics of -1 in selecting from a list don't seem to be consistent.

So I have a list of numbers

ls = range(1000)

The last element of the list if of course ls[-1] but if I take a sublist of that so that I get everything from say the midpoint to the end I would do

ls[500:-1]

but this does not give me a list containing the last element in the list, but instead a list containing everything UP TO the last element. However if I do

ls[0:10]

I get a list containing also the tenth element (so the selector ought to be inclusive), why then does it not work for -1.

I can of course do ls[500:] or ls[500:len(ls)] (which would be silly). I was just wondering what the deal with -1 was, I realise that I don't need it there.

1
35
8/10/2010 4:23:59 PM

Accepted Answer

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

The 10th element is ls[9], in ls[0:10] there isn't ls[10].

78
8/13/2014 2:46:07 PM

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]

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon