enumerate()

The enumerate function enumerates elements in an iterable. We can use the enumerate function easily with

enumerate(iterable, start=#)

and expect the iterable to be enumerated. There are a few use cases you should be familiar with.

Example 1 Enumerate a list of names


In [4]:
names = ["Pelsmajor", "Rudy", "Ali", "Derulo"]
names_numbers = list(enumerate(names))
print(names_numbers)


[(0, 'Pelsmajor'), (1, 'Rudy'), (2, 'Ali'), (3, 'Derulo')]

Example 2 Let's do the example before, but start at a more "human readable" 1.


In [6]:
names = ["Pelsmajor", "Rudy", "Ali", "Derulo"]
names_numbers = list(enumerate(names, start=1))
print(names_numbers)


[(1, 'Pelsmajor'), (2, 'Rudy'), (3, 'Ali'), (4, 'Derulo')]

Example 3 As opposed to a counter! Instead of making a counter variable, you can specify enumerate(iterable) in your for statement. We know that enumerate returns a tuple of (item no., item) so we can unpact the tuple by specifying a count and item variable in the loop.


In [8]:
vacation = ["Bahamas", "New York", "Seoul", "Shanghai", "Bangkok", "London", "Islamabad", "Quebec", "Mumbai"]

for count, item in enumerate(vacation):
    print("{}, {}".format(count, item))


0, Bahamas
1, New York
2, Seoul
3, Shanghai
4, Bangkok
5, London
6, Islamabad
7, Quebec
8, Mumbai