Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reverse Indexing in Python?

Tags:

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?

like image 456
Mohammad Moghimi Avatar asked Jul 12 '13 07:07

Mohammad Moghimi


People also ask

What is reverse indexing in Python?

Python enables reverse or negative indexing for the list elements. Thus, python lists index in opposite order. The python sets -1 as the index value for the last element in list and -2 for the preceding element and so on. This is called as Reverse Indexing.

How do you reverse a list in Python indexing?

Python comes with a number of methods and functions that allow you to reverse a list, either directly or by iterating over the list object. You'll learn how to reverse a Python list by using the reversed() function, the . reverse() method, list indexing, for loops, list comprehensions, and the slice method.

What is reverse indexing in database?

In database management systems, a reverse key index strategy reverses the key value before entering it in the index. E.g., the value 24538 becomes 83542 in the index.

How do you reverse data in Python?

In Python, there is a built-in function called reverse() that is used to reverse the list. This is a simple and quick way to reverse a list that requires little memory. Syntax- list_name. reverse() Here, list_name means you have to write the name of the list which has to be reversed.


1 Answers

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]
>>> 
like image 172
zhangyangyu Avatar answered Oct 03 '22 17:10

zhangyangyu