Python Forum

Full Version: sequence slicing problem
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello everyone, I have a simple question about sequence slicing and do not get why the following happens, please help me with that:
A very simple question:
>>> numbers=[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> numbers[:5:-2]
[10, 8]
I am very confused about this result. Here is what I thought should happen:
The operation numbers[:5:-2] means I get [1, 2, 3, 4, 5] from the 1. Part(numbers[:5]), and then from the end to the beginning get every second element([1, 2, 3, 4, 5]) backwards, so I should get [5, 3, 1], why the result is [10, 8]?
Please point out where I understand wrong.
Thanks.
As I understand it, the negative step effectively reserves the sequence. Then, it iterates over the reserved sequence until it reaches the fifth index. You may expect that to be [10, 8, 6], but counting backwards through the sequence starts at index -1 so the 6 gets cut off.

To achieve the desired output, you'll need to do this:

numbers[:5][::-2]
According to the documents:

s[i:j:k]

5.The slice of s from i to j with step k is defined as the sequence of items with index x = i + n*k such that 0 <= n < (j-i)/k. In other words, the indices are i, i+k, i+2*k, i+3*k and so on, stopping when j is reached

The last sentence says that if k (step) is negative, we start at the end and work back toward j (stop).

To do what you want you need to do two slices.

numbers[:5][::-2]
>>> numbers=[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> numbers[4::-2]
[5, 3, 1]
Ummm. Duh, (Smack!) I guess you could specify where you want to start counting down.