Python's Enumerate Function
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, a string, or a set, and returns an enumerate object containing a number of tuples: one for each item in the iterable. Each tuple contains an integer counter, and a value from the iterable.
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.
The most common place to find enumerate
being used is within something like a for loop, with the tuples inside the enumerate object destructured into two separate loop variables.
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'}
Wrapping up
If you're interested in learning more cool tricks like this, check out our Complete Python Course, or come join us on our Discord server. We'd love to have you!
There's also a form down below for signing up to our mailing list. If you like what we do, it's a great way to stay up to date with all our content, and we also share discount codes for our courses with our subscribers, ensuring they always get the best deals on our courses.