Loops in Python— Back to Basics

A deep dive into loops.

Zoltan Guba
Geek Culture
6 min readJan 3, 2022

--

Having strong fundamentals is essential in all professions — being a professional data wrangler is no different. Having the basics covered from time to time is always a good idea, either being a beginner or an advanced user. In this post, I’m going to cover loops.

Photo by Bru-nO from pixabay

Loops

In a nutshell, a loop is a set of instructions executed over and over again until a given condition is met. This condition can be anything: a certain number of executions (eat 10 donuts) or a condition that can be fulfilled after an unknown number of executions (eat donuts until you can hear your glucose level skyrocket).

Reasons to use loops can vary, for example: not wanting to repeat the code you need to execute multiple times, not knowing how many times a code block needs to be executed, or you have a program that needs the main loop to run continuously until the user decides that the program should stop.

Two types of loops are used in Python — the while and the for loop. Both of them can be expanded with a (bit strangely named) else clause, and the for loop actually has a very interesting version living in Python under the name comprehension. I will walk you through these concepts in the following post, as well as the usage of the continue and break statements.

While loop

The while loop is executed as long as the expression provided in the loop evaluates true.

Screenshot by Author

The below breakdown helps the overview of the things going on a little bit:

Screenshot by Author

And here is a flowchart for you to have a simplified view of the logic:

Screenshot by Author

The logical test returning boolean value can be anything really, it only depends on the context the code is used in. One important note is that unless this is your explicit desire, you should not forget to change the value(s) being tested in the main expression, otherwise you would end up in a so-called infinite loop, one that can be stopped executing only by the termination of the interpreter.

If you would like to keep me caffeinated for creating more content like this please consider to support me, with just a coffee.

For loop

The for loop is a special tool in Python since the logic behind is not the same you might expect coming from other languages. The for loop here is used to iterate through an iterable or iterator object (like a list, dictionary, a string, and so on), then executing a block of code most likely using the elements in the object. To get a little bit technical, the for statement yields an iterator object, and this iterator is providing the items from the original sequence or iterable.

Screenshot by Author

Else clause

The optional (!) else clause at the end of either the while or the for loop gives us the ability to execute a block of code after the main loop finished execution without hitting a break statement. This might seem a bit redundant, but using the else instead of other logical checks after the loop to see if it ran its full course or something broke the execution can actually come very handy.

Break statement

Sometimes we have situations when we do not want our loops to run until the predefined end criterion is met or the iterator in our for loop runs out of stuff. The break statement gives us the ability to terminate the execution of the innermost enclosing loop including the else statements as well.

Screenshot by Author

Continue statement

While break terminates the entire loop it is enclosed in, with continue you can stop one iteration in the loop from execution, and then make the loop jump to the next iteration.

Screenshot by Author

Note that with calling continue the else clause is being executed at the end.

Comprehensions

One of the most Pythonic things to do is using comprehension, at least in my humble opinion. Four types exist: list, dictionary, set, and generator comprehensions.

A comprehension is essentially a shorter syntax for creating an iterable or iterator based on another. The reason I am mentioning them in an article on loops is that the idea is that with comprehension you are creating an object by looping through another one — with a for loop.

List comprehension

To give the most basic example, imagine you have a list (L1) of integers and you want to have a new list (L2) of the squared value -1 of the integers in L1. The most basic solution would be a loop to do the job:

Screenshot by Author

List comprehension offers a more elegant way to do the same:

Screenshot by Author

The syntax might be a bit fuzzy at first, but it is actually rather straightforward:

Picture by Author

When you apply condition in the expression it gets a little gnarly, not too bad though:

Screenshot by Author

The breakdown makes it clearer:

Picture by Author

Since this is not a comprehension article I will just touch on the three other types, but with the above breakdown, I think this can serve as a great introduction.

Dictionary comprehension

Here we are creating a dictionary instead of a list (surprisingly enough) — the only tricky part might be to keep in mind that with the loop in the comprehension expression you need to create key:value pairs for each item in the starting iterable:

Screenshot by Author

It would make sense, and you totally can use multiple iterables to create the dictionary:

Screenshot by Author

Set comprehension

Set comprehension is very similar to list comprehension, with the exception that you put the expression in curly brackets, and of course, you won’t have any duplications at the end:

Screenshot by Author

Generator comprehension

Just like the previous one, generator comprehensions are just like list comprehensions in terms of syntax, besides the fact that you put simple braces around the expression:

Screenshot by Author

The real power comes from memory management: as you can see (and as you might have expected when creating a generator) here we do not have an entire created list in memory: instead, we have a generator only that can yield each element in it one by one:

Screenshot by Author

This can come super handy when you need to perform operations on a very large number of items, and storing all the outputs in memory at the same time would be difficult.

Thank you for taking the time to go through this article — I hope you have found value in it, regardless of whether you are a beginner just starting to get familiar with the basics or an advanced Python user in need of a lighter reminder of the basics.

--

--