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

232,626

Solution 1

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

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

Solution 2

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]

Solution 3

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] doesn't 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).

Solution 4

when slicing an array;

ls[y:x]  

takes the slice from element y upto and but not including x. when you use the negative indexing it is equivalent to using

ls[y:-1] == ls[y:len(ls)-1]

so it so the slice would be upto the last element, but it wouldn't include it (as per the slice)

Solution 5

It seems pretty consistent to me; positive indices are also non-inclusive. I think you're doing it wrong. Remembering that range() is also non-inclusive, and that Python arrays are 0-indexed, here's a sample python session to illustrate:

>>> d = range(10)
>>> d
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> d[9]
9
>>> d[-1]
9
>>> d[0:9]
[0, 1, 2, 3, 4, 5, 6, 7, 8]
>>> d[0:-1]
[0, 1, 2, 3, 4, 5, 6, 7, 8]
>>> len(d)
10
Share:
232,626

Related videos on Youtube

Matti Lyra
Author by

Matti Lyra

I am a PhD student at the University of Sussex studying Computational Linguistics. My research topic is "Topical Subcategory Structure in Text Classification"

Updated on November 23, 2021

Comments

  • Matti Lyra
    Matti Lyra over 2 years

    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.

    • Christopher Hunter
      Christopher Hunter over 2 years
      Note that this is an older question and some behavior is specific to python2. In python3 the equivalent would be ls = list(range(1000))