python list access

Python accesses the list by index

Since the list is an ordered collection, we can use a list to indicate the three students in the class from high to low:

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

So how do we get the class N students from the list? The method is to get the specified element in the list through the index.

It is important to note that the index starts at 0, that is, the index of the first element is 0, the index of the second element is 1, and so on.

Therefore, to print the first classmate’s name, use L[0]:

>>> print L[0]

To print the name of the second classmate, use L[1]:

>>> print L[1]

To print the name of the third classmate, use L[2]:

>>> print L[2]

To print the name of the fourth classmate, use L[3]:

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

Reported wrong! IndexError means that the index is out of range because the above list has only 3 elements and the valid index is 0, 1, 2.

Therefore, when using the index, be careful not to cross the border .

Leave a Reply

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