A simple way to get a list subscript and its value from Python _python

Source: Internet
Author: User
Tags in python

When traversing a sequence in python, we usually take the following approach:

For item in sequence:
    process (item)

If you want to take the location of an item, you can write this:

For index in range (len (sequence)):
    process (Sequence[index])

Another better way is to use the enumerate function built in Python:

Enumerate (sequence,start=0)

In the above function, sequence is an iterative object, which can be a list, a dictionary, a file object, and so on. Enumerate returns a tuple of subscript and item:

>>> seasons = [' Spring ', ' Summer ', ' Fall ', ' Winter ']
>>> list (Enumerate (seasons)) [(0, ' Spring '), (1, ' Summer '), (2, ' Fall '), (3, ' Winter ')]
>>> list (Enumerate (seasons, Start=1)) [(1, ' Spring ')], (2, ' Summe R '), (3, ' Fall '), (4, ' Winter ')]

The first example of the article can then be written in this way:

For Index,item in Enumerate (sequence):
    print Index,item

Above this python gets the list subscript and its value the simple method is the small series to share to everybody's content, hoped can give everybody a reference, also hoped that everybody supports the cloud habitat community.

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.