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?
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.
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.
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.
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.
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]
>>>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With