1
In [122]: a = range(10)

In [123]: a[: : -1]
Out[123]: [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]

Could you explain the expression a[: : -1]?

a[:] is clearly understandable -> "start form the beginning(space before the colon) and retrieve the list upto the end (space after the colon)"

But I am not getting what the two colons are actually doing in the expression a[: : -1].

Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
  • 1
    possible duplicate of [What does 'result\[::-1\]' mean?](http://stackoverflow.com/questions/13365424/what-does-result-1-mean) – Wooble Feb 18 '14 at 23:59
  • My question is a bit different. In [124]: a[: : 2] Out[124]: [0, 2, 4, 6, 8] if we consider i as the step size in a[: : i], it is clear that output will be like [start, start + step, start + 2*step.... and so on]. So in a[: : -1] it must be like [0, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0] But this is not the case –  Feb 19 '14 at 00:11
  • Go through this - http://stackoverflow.com/questions/509211/pythons-slice-notation – Shan Valleru Feb 19 '14 at 00:24
  • finally got it!!! The negative value of step changes the interpretation of start and end. So start becomes end and end becomes start in case of negative step –  Feb 19 '14 at 00:37
  • Does this answer your question? [Understanding slicing](https://stackoverflow.com/questions/509211/understanding-slicing) – Karl Knechtel Aug 29 '22 at 13:47

2 Answers2

0

The third argument (after two :'s) is the step size. -1 can be interpreted as stepping backwards. In other words, reversing the list.

Try with -2 step size i.e., a[::-2], You'll get:

[9, 7, 5, 3, 1]

Hope this helps.

More elaborate answers and explanations here Explain Python's slice notation

Community
  • 1
  • 1
Raiyan
  • 1,589
  • 1
  • 14
  • 28
  • In [124]: a[: : 2] Out[124]: [0, 2, 4, 6, 8] if we consider i as the step size in a[: : i], it is clear that output will be like [start, start + step, start + 2*step.... and so on]. So in a[: : -1] it must be like [0, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0] But this is not the case... –  Feb 18 '14 at 23:50
  • Yup, that's because when you set the step size to 2, the indices are counted 2 apart. 0, then 2, then 4 and so on till 8. – Raiyan Feb 18 '14 at 23:52
  • @neel101: this is my comment after your edit. In case of a[::i] where i<0, the counting start from the end of the list. In other words, start is length_of_list-1 instead of 0. SO we have 9 to begin with. Then its 8, 7, 6 ... 0 – Raiyan Feb 21 '14 at 04:48
0

A slice takes three arguments, just like range: start, stop and step:

[0, 1, 2, 3, 4, 5][0:4:2] == list(range(0, 4, 2)) # every second element from 0 to 3

The negative step causes the slice to work backwards through the iterable. Without a start and stop (i.e. just the step [::-1]) it starts from the end, as it is working backwards.

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437