The Art of Writing Loops in Python

Simple is better than complex

Yang Zhou
TechToFreedom

--

Photo by Jie on Unsplash

The for loop is a very basic control flow tool of most programming languages. For example, a simple for loop in C looks like the following:

int i;
for (i=0;i<N;i++)
{
//do something
}

There are no other ways to write a for loop more elegantly in C. For a complex scenario, we usually need to write ugly nested loops or define lots of assistant variables (like the i in the above code).

Fortunately, when it comes to Python, things become much more convenient. We have many tricks to write much more elegant loops and they do make our lives easier. In Python, nested loops are not inevitable, assistant variables are not necessary, and we can even customise a for loop by ourselves.

This article will introduce some of the most helpful tricks for writing loops in Python. Hopefully, it can help you feel the beauty of Python.

Get Indexes and Values at Once

A common scenario of using a for loop is to get indexes and values from a list. When I started learning Python, I wrote my code like the following:

for i in range(len(my_list)):
print(i, my_list[i])

--

--