Python Enumerate index iterations

Source: Internet
Author: User
Tags python enumerate

Tag:ar    using    for   on   art    code    ad   python    method    

Index iterations
In Python, iterations are always taken out of the element itself, not the index of the element.
For an ordered set, the element is indeed indexed. Sometimes we really want to get the index in the for loop, what do we do?
The method is to use the enumerate () function:
>>> L = [' Adam ', ' Lisa ', ' Bart ', ' Paul ']
>>> for index, name in enumerate (L):
... print index, '-', name
...
0-adam
1-lisa
2-bart
3-paul
Using the enumerate () function, we can bind both index and element name in the For loop. However, this is not a special syntax for enumerate (). In fact, the enumerate () function puts:
[' Adam ', ' Lisa ', ' Bart ', ' Paul ']
Into something like this:
[(0, ' Adam '), (1, ' Lisa '), (2, ' Bart '), (3, ' Paul ')]
Therefore, each element of an iteration is actually a tuple:
For T in enumerate (L):
index = t[0]
name = T[1]
Print index, '-', name
If we know that each tuple element contains two elements, the for loop can be further abbreviated as:
For index, name in enumerate (L):
Print index, '-', name
This not only makes the code simpler, but also reduces the number of two assignment statements.
It can be seen that the index iteration is not really indexed, but instead the enumerate () function automatically turns each element into a tuple (index, Element) and iterates over the index and the element itself.

Python Enumerate index iterations

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.