Skip to content Skip to sidebar Skip to footer

Python (2.x) List / Sublist Selection -1 Weirdness

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 nu

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:

-1 isn't special in the sense that the sequence is read backwards, it rather wraps around the ends. Such that minus one means zero minus one, exclusive (and, for a positive step value, the sequence is read "from left to right".

so for i = [1, 2, 3, 4], i[2:-1] means from item two to the beginning minus one (or, 'around to the end'), which results in [3]. The -1th element, or element 0 backwards 1 is the last 4, but since it's exclusive, we get 3.

I hope this is somewhat understandable.

Post a Comment for "Python (2.x) List / Sublist Selection -1 Weirdness"