Help with Start-Stop-Step slicing | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Help with Start-Stop-Step slicing

Hi I'm having a bit of difficulty to understand slicing with a negative step. Could somebody help me understanding these two examples? EXAMPLE ONE print('game of dice'[::-3]) #result: edom EXAMPLE TWO a=['a','d','b','c'] a=a[2:0:-1] print(a) #result: ['b','d'] Thank you in advance!

4th Apr 2020, 6:36 PM
Salvatore Junior Iaccarino
Salvatore Junior Iaccarino - avatar
3 Answers
+ 2
Slice syntax is something like this: list[start:stop:step] So the slice begins with the element at index "start" (if negative, then count from the end, -1 meaning the last element) The index "stop" is non-inclusive, so never actually selected. Same as with the range() function. The "step" is the direction and how many elements are skipped. So in summary, a[2:0:-1] means start with element at index 2: 'b' stop before you reach index 0: 'a' step backwards by one element So index 2 and 1 are included in the slice, giving ['b', 'd']
4th Apr 2020, 7:05 PM
Tibor Santa
Tibor Santa - avatar
+ 1
game of dice In reverse slicing, started from last index value as -1 step count is -3, so Index at -1 is e -1 + -3 = -4 is d -4 + -3 = -7 is o -7 + -3 =-10 is m Output is edom Or ex2: Simply like 'a' index at 0, - 4 'd' 1 - 3 'b' 2 - 2 'c' 3 -1 a[[2,0,-1] means extract reverse starting at index 2 to 0(not included) So 'b' 'd' output
4th Apr 2020, 7:01 PM
Jayakrishna 🇮🇳
+ 1
Tibor Santa and Jayakrishna🇮🇳, Thank you both very much for your clear explanations and for the time spent writing them. While I was sure the slicing was moving backwards, I had them wrong for two very stupid reasons... (I'm even ashamed of saying them😄) Example1: forgot to count the spaces. Example2: forgot that the "end" position is not included. Thank you again!
4th Apr 2020, 8:52 PM
Salvatore Junior Iaccarino
Salvatore Junior Iaccarino - avatar