Python Forum
sequence slicing problem - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: sequence slicing problem (/thread-26307.html)



sequence slicing problem - qliu - Apr-27-2020

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.


RE: sequence slicing problem - stullis - Apr-27-2020

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]



RE: sequence slicing problem - deanhystad - Apr-27-2020

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]


RE: sequence slicing problem - Yoriz - Apr-27-2020

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



RE: sequence slicing problem - deanhystad - Apr-27-2020

Ummm. Duh, (Smack!) I guess you could specify where you want to start counting down.