Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
sequence slicing problem
#1
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.
Reply
#2
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]
Reply
#3
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]
Reply
#4
>>> numbers=[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> numbers[4::-2]
[5, 3, 1]
Reply
#5
Ummm. Duh, (Smack!) I guess you could specify where you want to start counting down.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  String slicing problem Ollew 4 2,741 Sep-08-2018, 08:07 PM
Last Post: Ollew
  Problem with slicing string YatishK 2 3,360 Apr-24-2017, 09:46 AM
Last Post: YatishK

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020