enumerate()
is a useful function to make an iterator when used with a for
loop. Here we explain different ways of using
enumerate()
using a python list. enumerate()
acts as an iterator yielding a tuple (index,element)
when applied on a list.
Consider the list:
myList = ['a', 'b', 'c', 'd']
Let’s make an iterator using myList
:
iterator = enumerate(myList) print(next(iterator)) print(next(iterator))
(0, 'a') (1, 'b')
Passing the iterator to list will yield the entire list
list(enumerate(myList))
[(0, 'a'), (1, 'b'), (2, 'c'), (3, 'd')]
Passing an integer argument as enumerate(myList,n)
will force the index to start from n
as shown below:
list(enumerate(myList,100))
[(100, 'a'), (101, 'b'), (102, 'c'), (103, 'd')]
Using enumerate()
with a for
loop
for idx, char in enumerate(myList): print(idx, char)
0 a 1 b 2 c 3 d
Passing the additional argument n
is usefule if you want start the loop from a particular value.
for idx, char in enumerate(myList,100): print(idx, char)
100 a 101 b 102 c 103 d