In this tutorial, we will discuss about the enumerate() function in python programming language with the help of examples.
Python enumerate() function
The built-in python function is used to return an enumerate object by adding counter to the iterable objects. Simply, to keep a count of iterations, method is used. By using the list() and tuple() functions we can convert the enumerate object into list and tuple. The enumerating objects can also be used for loops directly.
Syntax
enumerate(iterable, start=0)
Parameters of enumerate() function in python
The function in python takes two arguments or parameters i.e.,
• - any object or sequence which supports iteration.
• - value from which the counting starts. is the default value.
Return value of Python enumerate() function
The python function is used to return an enumerate object by adding counter to the iterable objects.
By using the list() and tuple() functions we can convert the enumerate object into list and tuple.
Example 1: How Python enumerate() function works?
lang = ['Python', 'Java', 'Swift']pro_lang = enumerate(lang)
print(type(pro_lang))
print(list(pro_lang))
pro_lang = enumerate(lang, 10)
print(list(pro_lang))
Output
<class 'enumerate'>[(0, 'Python'), (1, 'Java'), (2, 'Swift')]
[(10, 'Python'), (11, 'Java'), (12, 'Swift')]
Example 2: Looping Over an Enumerate object
lang = ['Python', 'Java', 'Swift']for program in enumerate(lang):
print(program)
print('\n')
for count, program in enumerate(lang):
print(count, program)
print('\n')
# changing default start value
for count, program in enumerate(lang, 100):
print(count, program)
Output
(0, 'Python')(1, 'Java')
(2, 'Swift')
0 Python
1 Java
2 Swift
100 Python
101 Java
102 Swift