Python accesses list by index

Source: Internet
Author: User

Tag: Ack Index des access specifies Lin pre first so

Python accesses list by index

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

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

So how do we get the names of the nth-named students from the list? The method is to get the specified element in the list by index.

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

Therefore, to print the first name of a classmate, use L[0]:

>>> Print L[0]adam

To print the name of the first two students, use L[1]:

>>> Print L[1]lisa

To print the name of the first three students, use L[2]:

>>> Print L[2]bart

To print the name of the first four students, use L[3]:

>>> Print L[3]traceback (most recent call last):  File "<stdin>", line 1, in <module>indexerror:l Ist index out of range

The error! Indexerror means that the index is out of range because the list above has only 3 elements, and the valid index is 0,1,2.

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

Python accesses list by index

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.