Using the enumerate function in python to traverse element instances

Source: Internet
Author: User

This is a built-in function of python. I found it while reading the book. mark it.
When we need to traverse both indexes and elements, we can consider using the enumerate function. The enumerate function accepts an object that can be traversed, such as a list or string.

For example, if we have a list of ["one", "two", "there"], we need to add its number before each element in the list.
Copy codeThe Code is as follows:
I = 0
Seq = ["one", "two", "three"]
For element in seq:
Seq [I] = '% d: % s' % (I, seq [I])
I + = 1
Print seq

['0: one', '1: two', '2: three ']

Using the enumerate function, we can simplify our code and eliminate the need to define temporary variables for counting.
Copy codeThe Code is as follows:
Seq = ["one", "two", "three"]
For I, element in enumerate (seq ):
Seq [I] = '% d: % s' % (I, seq [I])
Print seq

['0: one', '1: two', '2: three ']
The drama is not over yet. The charm of python is here. Let's write a Phthonic script.
Copy codeThe Code is as follows:
Seq = ["one", "two", "three"]
Print ['% d: % s' % (I, element) for I, element in enumerate (seq)]

['0: one', '1: two', '2: three ']
Well, python's traversal technology is very flexible. I can't finish talking about it in a few words. I need to turn off the lights and get my sleep.

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.