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?

Kenly
  • 24,317
  • 7
  • 44
  • 60
  • 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]` – Padraic Cunningham Feb 03 '16 at 19:42
  • 4
    `th = l[2::3]` following your logic – Mohammed Aouf Zouag Feb 03 '16 at 19:43
  • 0 % 3 = 0, 3 % 3 = 0...etc the math works out. – Mike McMahon Feb 03 '16 at 19:44
  • 1
    @kuhe you can check the stackoverflow post [Explain Python's slice notation](http://stackoverflow.com/questions/509211/explain-pythons-slice-notation), there is some useful answers about python index/slice notation. – mgc Feb 03 '16 at 19:47

2 Answers2

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.

StephenTG
  • 2,579
  • 6
  • 26
  • 36
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).

banan3'14
  • 3,810
  • 3
  • 24
  • 47