-4

I have below list

l1 = [1,2,3,4,5,6,7,8,9]

I want to understand below result :-

>>> l1
[4:8:-2]

Please explain result of above slicing.

inspectorG4dget
  • 110,290
  • 27
  • 149
  • 241
Ibney Hasan
  • 71
  • 1
  • 1
  • 4

1 Answers1

1

slicing is [start:stop:step] do like this, When you are steping it from backward then you have to take index from back,

>>> l1 = [1,2,3,4,5,6,7,8,9]
>>> l1[8:4:-2]
[9, 7]

You are asking to start from index 4 till index 8 by step -2, so you are asking to get index 8 and 6 and avoiding index 4.

Vishnu Upadhyay
  • 5,043
  • 1
  • 13
  • 24
  • @lbney Hasan, because you are asking from index `4` to `8` by negative count, what you are doing by giving `step = -2`, start from for `4`, then `4-2`, `2-2` **(-2 is stepping)**, till `8th` index. Now think how it will reach to 8th index. – Vishnu Upadhyay Nov 09 '14 at 05:24
  • if it will start from 4 index then first values should be return 4 index values is 5 then it will check 4-2 2-2 up 8th. Why result is [] – Ibney Hasan Nov 09 '14 at 05:41
  • @lbney Hasan python checks first the slicing you are applying, complete statement will parse, and here parsing is wrong, that's why it is thrwoing a vacant list. – Vishnu Upadhyay Nov 09 '14 at 05:59
  • Thanks Vishnu .Now i understand . – Ibney Hasan Nov 09 '14 at 06:24
  • @lbney Hasan If you are seeing any correct mark option at this page then click on it. – Vishnu Upadhyay Nov 09 '14 at 07:11