Python reverse access list

Python’s reverse access list

We still use a list to indicate the three students in the class from high to low:

>>> L = ['Adam', 'Lisa', 'Bart']

At this time, the teacher said, please ask the students with the lowest scores to stand up.

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]

Is there an easier way?


Bart is the last one, commonly known as the last, so we can use the index -1 to represent the last element:

>>> print L[-1]

Bart said that he was lying down.

Similarly, the penultimate is represented by -2, the third to third is represented by -3, and the fourth to fourth is represented by -4:

>>> print L[-2]
>>> print L[-3]
>>> print L[-4]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: list index out of range

L[-4] reported an error because the fourth last does not exist, and there are only three elements in total.

When using reverse index, be careful not to cross the boundary .

Leave a Reply

Your email address will not be published. Required fields are marked *