Don’t deliberate, just Enumerate

Don’t deliberate, just Enumerate

A quick blog on for iterations in Python

“How does one easily loop through an iterable and with index?”. This is a common question people who are just starting their Python may ask. One will quickly learn that Python only has the for loop which, by default does not give the user index. In this blog post we will learn a sophisticated, simple and pythonic method to answer this trivial question.

Python gives us the ‘for’ loop which allows us to iterate over pretty much anything. For example:

Iterating over a string
Iterating over a range of numbers
Iterating over a list of names

Now this is all great but each one of those loops did not give us index. It just looped over until all we reached the end.

How not to get Index

I see many people (I was also originally a culprit) get index within their loops by trying to adapt a for loop from other languages like C# and would write something similar to this:

Showing how to iterate with index the bad way!

Whilst the above code works and does in fact give us index by looping over the length of the input and getting the value in the loop by indexing the input data, it is not the most Pythonic as there is a much simpler and cleaner way to do it.

Introducing Enumerate. How to get index

A much cleaner and simpler way to achieve this is to make use of the built in enumerate method.

Showing the tuples created by the enumerate method

By casting our names list to an enumerate object Python has automatically created a tuple for each of the members of our list and made the index we desire the first member of the tuple. Now, taking this one step further, and using the neat tuple unpacking trick, we can break these tuples apart and get the final answer that we require.

Now we have the index and our loop the possibilities are many.

Leave a Reply

Your email address will not be published. Required fields are marked *