##### sequence slicing problem
 sequence slicing problem qliu Unladen Swallow Posts: 2 Threads: 2 Joined: Apr 2020 Reputation: Apr-27-2020, 08:14 PM (This post was last modified: Apr-27-2020, 09:32 PM by Yoriz.) 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 stullis Minister of Silly Walks Posts: 444 Threads: 1 Joined: Sep 2018 Reputation: Apr-27-2020, 09:08 PM 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 deanhystad So-and-so of the Yard Posts: 2,326 Threads: 11 Joined: Feb 2020 Reputation: Apr-27-2020, 09:23 PM 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 Posts: 1,839 Threads: 33 Joined: Sep 2016 Reputation: Apr-27-2020, 09:30 PM ```>>> numbers=[1, 2, 3, 4, 5, 6, 7, 8, 9, 10] >>> numbers[4::-2] [5, 3, 1]``` Reply deanhystad So-and-so of the Yard Posts: 2,326 Threads: 11 Joined: Feb 2020 Reputation: Apr-27-2020, 09:50 PM 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 1,449 Sep-08-2018, 08:07 PM Last Post: Ollew Problem with slicing string YatishK 2 2,122 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