Reverse Indexing in Python?
Reverse Indexing in Python?
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]
>>>
Omit the end index:
print a[15::-1]
Reverse Indexing in Python?
In Python2.x, the simplest solution in terms of number of characters should probably be :
>>> a=range(20)
>>> a[::-1]
[19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
Though i want to point out that if using xrange(), indexing wont work because xrange() gives you an xrange object instead of a list.
>>> a=xrange(20)
>>> a[::-1]
Traceback (most recent call last):
File <stdin>, line 1, in <module>
TypeError: sequence index must be integer, not slice
After in Python3.x, range() does what xrange() does in Python2.x but also has an improvement accepting indexing change upon the object.
>>> a = range(20)
>>> a[::-1]
range(19, -1, -1)
>>> b=a[::-1]
>>> for i in b:
... print (i)
...
19
18
17
16
15
14
13
12
11
10
9
8
7
6
5
4
3
2
1
0
>>>
the difference between range() and xrange() learned from source: http://pythoncentral.io/how-to-use-pythons-xrange-and-range/
by author: Joey Payne