A Cursory Look at Enumerate()

Improving my coding skills to be more Pythonic

Photo by David Wright on Unsplash

Preparing for a technical interview is an ongoing endeavor and part of a growth mindset to keep learning and improving. I came across an article on Real Python on “How to Stand Out In a Python Coding Interview” and was intrigued right away. The advice was to select the right built-in function for the job and enumerate() was top of the list. I recall the first time I came across enumerate() in my Data Science course and felt a little perplexed by it. Clearly now was the time to dive in and learn to use it properly!

The challenge was to iterate with enumerate() instead of using range(). But first: what is enumerate() and what does it do?

On to the challenge of using enumerate() in place of range(). I pulled out my previously written code for the “FizzBuzz” problem (yes, the one with all the if statements!) and added a list of numbers to run the code with.

numbers = [45, 22, 14, 65, 97, 72]

Here is my code using range():

And the result:

result from running code
result from running code

Notice, only the index is available (and the corresponding “fizz”, “buzz” or “fizzbuzz”) and not the number itself.

And here is the code snippet using enumerate():

Code using enumerate

And here the result — the buzz/fizz/fizzbuzz word, the integer and it’s index:

Result from code
Result from code

This is a much cleaner snippet of code to read and more idiomatic. And more Pythonic!

Let’s look at other ways enumerate can be used: on strings and tuples, and to create a dictionary from a list:

# Enumerate on a stringstring = ‘I love python’for i, j in enumerate(string):
Enumerate on a string
# Enumerate on a tupletupl = [(10,’a’), (5,’b’), (8,’c’),(2,’d’)]for index, (count,alpha) in enumerate(tupl):
print(index, count, alpha)
Enumerate on a tuple
# Create a dict from list with enumerate
list2 = [1,2,3,4]
dict2 = dict(enumerate(list2))
Enumerate on a list to create a dictionary

And finally, just for fun, I compared the time of a very simple action using a for loop and enumerate on a random list of 10000 integers:

For a result of the difference in time of:


In conclusion, this was a quick and dirty lesson on enumerate(), yet it helped me understand the concept more clearly and be prepared to use it confidently.