Python's enumerate function is an awesome tool that allows us to create a counter alongside values we're iterating over: as part of a loop, for example.

enumerate takes an iterable type as its first positional argument, such as a list or a set.

enumerate also takes an optional additional parameter called start, which can be provided as either a keyword or positional argument. If no start value is provided, enumerate begins counting from zero, making it a perfect tool for tracking the index of each item.

friends = ["Rolf", "John", "Anna"]

for counter, friend in enumerate(friends, start=1):
	print(counter, friend)

# 1 Rolf
# 2 John
# 3 Anna

The use of enumerate is not limited to just for loops, however. We can also make use of enumerate as part of a list comprehension, for example, or even passed in as an argument to dict.

friends = ["Rolf", "John", "Anna"]
friends_dict = dict(enumerate(friends))  # {0: 'Rolf', 1: 'John', 2: 'Anna'}

If you're interested in learning more cool tricks like this, check out our Complete Python Course. By following the link in this post, you can get the course for just $9.99, and we also have a 30 day money back guarantee. We'd love to have you!