Python's Reverse access list
We still use a list to score from high to low to show 3 students in the class:
>>> L = [' Adam ', ' Lisa ', ' Bart ']
At this time, the teacher said, please score the lowest students stand out.
To write code to accomplish this task, we can count the list first and find that it contains 3 elements, so the index of the last element is 2:
>>> Print L[2]bart
Is there a simpler way?
Yes!
Bart classmate is the last, commonly known as the Countdown first , so we can use the 1 index to represent the last element:
>>> Print L[-1]bart
Bart classmate says lying on the gun.
Similarly, the second-to-last use-2 means that the reciprocal third use-3 means that the penultimate fourth uses-4 means:
>>> print l[-2]lisa>>> print l[-3]adam>>> print l[-4]traceback (most recent call last): File "<stdin>", line 1, inch <module>indexerror:list index out of range
L[-4] Error, because the penultimate fourth does not exist, there are only 3 elements.
When using a reverse index, also be careful not to cross the border.
Python's Reverse access list