Last Updated on 2020-09-25 by Clay
Introduction
enumerate()
is a function often used in Python. Its usage is very simple, just only need use enumerate(iterable, start_index)
. The first parameter enters the iterable object, and the second parameter enters the first number to be counted (Calculate from 0 by default).
Let's take a look at a simple sample code.
enumerate() example code
# -*- coding: utf-8 -*-
List = ['a', 'b', 'c', 'd', 'e']
for value in enumerate(List):
print(value)
Output:
(0, 'a') (1, 'b') (2, 'c') (3, 'd') (4, 'e')
The output of enumerate()
is the number and the elements of the iterable object, as we have seen.
for value in enumerate(List):
print(type(value))
Output:
<class 'tuple'> <class 'tuple'> <class 'tuple'> <class 'tuple'> <class 'tuple'>
And the output is the tuple data type.
for value in enumerate(List, start=5):
print(value)
Output:
(5, 'a') (6, 'b') (7, 'c') (8, 'd') (9, 'e')
If we have set the starting value of the count, then we will see that the number returned by enumerate()
is different.
In addition, we can also separate index and value in the for loop:
for index, value in enumerate(List):
print(index)
for index, value in enumerate(List):
print(value)
Output:
0 1 2 3 4 a b c d e
The above is the basic introduction notes of enumerate()
in Python.