enumerate()
is one of Python's built-in functions for converting an iterable object (such as a list, tuple, string) into an enumeration object, and returns the index and value of each element.
Specifically, the function will enumerate each element in startingenumerate(iterable, start=0)
from index , and return an enumeration object containing tuples. Among them, represents the position of the current element in the iterable object, counting ; represents the value of the current element.start
iterable
(index, item)
index
start
item
Here is a simple demo example:
# Enumerate all elements and their indices in a list fruits = ['apple', 'banana', 'cherry'] for index, fruit in enumerate(fruits): print(index, fruit) # output: # 0 apple # 1 banana # 2 cherry
In the above code, enumerate()
the function is used to enumerate all elements and their indexes fruits
in . Since no start
parameter , it starts counting from 0 by default. The result of the run shows the index and name of each fruit in the list.
Another thing to note is for
that enumerate()
when using the function in a loop, you can use parentheses to split each tuple of the enumeration object into variables. For example, the following syntax can be used:
pythonCopy code
# Enumerate all elements and their indexes in a list, and split the tuples into variables
fruits = ['apple', 'banana', 'cherry']
for index, fruit in enumerate(fruits):
print(index, fruit)
In this way, the index
and fruit
to represent the index and value of the current element, and the code is more concise and easy to read.