tags:

views:

76

answers:

4

The following code include the last number.

>>> numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> numbers[::3]
[1, 4, 7, 10]

Why does not includet the last number 2, like 10, 8, 6, 4, 2?

>>> numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> numbers[:1:-2]
[10, 8, 6, 4]
+2  A: 

:: is walking over the list with N steps. So it's 1, then it goes to 4, etc. If you want to step with 2 backwards, you want [::-2]

wvd
+3  A: 

It seems that the slice operator is simply non-inclusive of the second argument. In other-words, your 1 should be a 0:

>>> numbers = [1,2,3,4,5,6,7,8,9,10]
>>> numbers[:1:-2]
[10, 8, 6, 4]
>>> numbers[:0:-2]
[10, 8, 6, 4, 2]

Hope that helps :)

For further info, see Note 5 here.

David Antaramian
Why not [::-2] instead?
wvd
That works too, of course, but my point was to show that the argument `1` was the issue. Plus, making general statements like "Python will use 0 where arguments are lacking" are likely to be troublesome.
David Antaramian
A: 

Because the slice excludes the second number from the range. a[1:4] fetches elements 1, 2 and 3. Likewise, a[10:6:-1] fetches elements 10, 9, 8 and 7, but not 6.

Marcelo Cantos
numbers[10:6:-1] outputs 10, 9, 8 not 7.
shin
I was referring to the elements in positions 10 through 7 in some arbitrary array, `a`.
Marcelo Cantos
+1  A: 

Python is pretty consistent in following the pattern of sequence ranges being lower inclusive, upper exclusive. That is, if you say range(1,5) --> [1,2,3,4]. The lower index is included and the upper is excluded. This helps a lot with various kinds of off-by-one and fencepost errors. See wikipedia for a brief explanation of these kinds of problems.

Pierce