Reverse indexing in Python?

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

for instance

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?

+6
source share
6 answers

You can assign your variable None :

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

Omit End Index:

 print a[15::-1] 
+8
source

In Python2.x, the simplest solution in terms of character count should 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] 

Although I want to point out that when using xrange (), indexing will not work, because xrange () provides you with 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 that accepts changing the indexing of an 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 >>> 

difference between range () and xrange () obtained from source: http://pythoncentral.io/how-to-use-pythons-xrange-and-range/ author: Joey Payne

+2
source

EDIT : start and end are variables

I never understood this, but a (slightly hacked) solution would be:

 >>> a = range(5) >>> s = 0 >>> e = 3 >>> b = a[s:e] >>> b.reverse() >>> print b [2, 1, 0] 
0
source
 >>> a [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19] >>> print a[:6:-1] [19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7] >>> a[7] == a[:6:-1][-1] True >>> a[1] == a[:0:-1][-1] True 

So, as you can see, when you substitute the value in the start label: end: this will give you only [end] from start to finish.

As you can see here:

 >>> a[0:2:] [0, 1] 

-1 is the last value in a:

 >>> a[len(a)-1] == a[-1] True 
0
source

If you use negative indexes, you can avoid additional assignments using only your start and end variables:

 a = range(20) start = 20 for end in range(21): a[start:-(len(a)+1-end):-1] 
0
source

Source: https://habr.com/ru/post/949288/


All Articles