Improving my coding skills to be more Pythonic
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?
Enumerate is a handy little built-in Python function. It is used to loop over an iterable creating an automatic index. It is more pythonic and idiomatic, and less error-prone, than manual indexing. And it avoids problems of duplicate list entries.
For very large lists, the use of enumerate() avoids the action of traversing across large amounts of data, which can be inefficient.
Enumerate can be used on strings, tuples and lists. It is not ideal for dictionaries and sets because those constructs do not uses indexes.
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:
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():
And here the result — the buzz/fizz/fizzbuzz word, the integer and it’s index:
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 tupletupl = [(10,’a’), (5,’b’), (8,’c’),(2,’d’)]for index, (count,alpha) in enumerate(tupl):
print(index, count, alpha)
# Create a dict from list with enumerate
list2 = [1,2,3,4]
dict2 = dict(enumerate(list2))
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.