2

I am learning python, and I have a problem with list slice. when I try to get all element at the third position, I got the wrong one:

l = [9, 0, 7, 1, 7, 5, 5, 9, 8, 0]
th = l[::3]
>> [9, 1, 5, 0]

but in my logic it should be:

>> [7, 5, 8]

Why it returns a wrong result?

4
  • 3
    You are stepping 3 starting from the 0 index so you get what you ask for, to get what you want would be l[2::3], if it makes it simpler you are basically doing l[0:len(l):3] Commented Feb 3, 2016 at 19:42
  • 4
    th = l[2::3] following your logic Commented Feb 3, 2016 at 19:43
  • 0 % 3 = 0, 3 % 3 = 0...etc the math works out. Commented Feb 3, 2016 at 19:44
  • 1
    @kuhe you can check the stackoverflow post Explain Python's slice notation, there is some useful answers about python index/slice notation. Commented Feb 3, 2016 at 19:47

2 Answers 2

2

l[::3] means start at 0 and go till the end of list and step 3 each time so at each step, it will output item at indices 0, 3, 6, 9. Which corresponds to the result that Python returned back. try l[2::3] if you want your desired output (every third element starting from the third).

Sign up to request clarification or add additional context in comments.

Comments

2

The problem is that the Python slice operator starts at the first index (index 0), while you want it to start at the third (index 2). [2::3] should get what you want, as this will tell it to start at index 2 and take it and every third element after.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.