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)
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)
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))