Python enumerate index iteration code parsing, pythonenumerate

Source: Internet
Author: User
Tags python enumerate

Python enumerate index iteration code parsing, pythonenumerate

This article focuses on Python enumerate index iteration.

Index Iteration

In Python, iterations always extract the element itself, not the element index.

For ordered sets, the elements are indeed indexed. Sometimes, we really want to get the index in the for loop. What should 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 - Adam1 - Lisa2 - Bart3 - Paul

Using the enumerate () function, we can bind both the index and element name in the for loop. However, this is not a special Syntax of enumerate. In fact, the enumerate () function treats:

['Adam', 'Lisa', 'Bart', 'Paul']

It becomes similar:

[(0, 'Adam'), (1, 'Lisa'), (2, 'Bart'), (3, 'Paul')]

Therefore, each element of 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:

for index, name in enumerate(L):print index, '-', name

This not only simplifies the code, but also removes two value assignment statements.

It can be seen that index iteration does not really access by index. Instead, the enumerate () function automatically converts each element to a tuple such as index and element, and then iterates, both the index and the element itself are obtained.

Summary

The above is all about parsing the Python enumerate index iteration code. I hope it will be helpful to you. If you are interested, you can continue to refer to other related topics on this site. If you have any shortcomings, please leave a message. Thank you for your support!

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.