Mohammad Moghimi Mohammad Moghimi - 4 months ago 24
Python Question

Reverse Indexing in Python?

I know that a[end:start:-1] slices a list in a reverse order.

For example

a = range(20)
print a[15:10:-1] # prints [15, ..., 11]
print a[15:0:-1] # prints [15, ..., 1]


but you cannot get to the first element (0 in the example). It seems that -1 is a special value.

print a[15:-1:-1] # prints []


Any ideas?

Answer

You can assign your variable to None:

>>> a = range(20)
>>> a[15:None:-1]
[15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
>>>