Hello! !! This time I would like to write an article about the enumerate function of python. You can use the enumerate function to get the elements and order of a list or tuple in a for loop. In short, it is a function that returns the contents of lists and tuples and their order numbers. You can use the enumerate function to simplify your code and make it intuitive. Now, let's solve a simple problem with and without the enumerate function.
There is a regular presentation in the laboratory. I would like to go to the order of presentations in the order of this prepared list (array). However, since the order is not written in this list, it is not intuitive. So please output the name and the order of presentation.
Let's solve such a problem.
If you don't handle the enumerate function, you'll get code like this:
enumerate.py
publicator = ["haruto","sota","minato","yuto","riku","mei"]
num = len(publicator)
for i in range(num):
print(i+1,publicator[i])
1 haruto
2 sota
3 minato
4 yuto
5 riku
6 mei
It handles the len function, gets the number of arrays, and does a for loop.
Then, when dealing with the enumerate function of the main subject, the code looks like this.
enumerate.py
publicator = ["haruto","sota","minato","yuto","riku","mei"]
for i,pub in enumerate(publicator,1):
print(i,pub)
1 haruto
2 sota
3 minato
4 yuto
5 riku
6 mei
You don't have to use two variables, and I think it's easier to code when dealing with the enumerate function. By the way, the part of enumerate (publicator, 1) means that the order number of the array publicator starts from 1, so it is a convenient function because it does not have to be i + 1.
The enumerate function was handled in a for loop and returned the elements of lists and tuples and their order numbers. It's surprisingly convenient to write code.
In the second post of Qiita, it may be difficult to understand because I have never sent information such as blogs. From now on, I would like to disseminate information and improve my writing skills, and my dream is to become a person who can play with technology, so please watch with warm eyes. Thank you in advance. Well then!
Recommended Posts