Python enumerate index iterative code parsing

  • 2020-07-21 09:02:58
  • OfStack

This paper mainly studies the problem of Python enumerate index iteration, which is detailed as follows.

The index iteration

In Python, iteration is always pulling out the element itself, not the index of the element.

For ordered collections, the elements are indeed indexed. Sometimes we do 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 the index index and the 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']

It becomes something like:


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

Therefore, each element of the iteration is actually 1 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 shortened to:


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

Not only is the code simpler, but there are two fewer assignment statements.

As you can see, the index iteration is not really indexed either. Instead, the enumerate() function automatically turns each element into an tuple like (index, element).

conclusion

That is the end of this article on Python enumerate index iteration code parsing, I hope to help you. Interested friends can continue to refer to other related topics in this site, if there is any deficiency, welcome to comment out. Thank you for your support!


Related articles: