🚀 Think you’ve got what it takes for a career in Data? Find out in just one minute!

Mastering Control Flow: The Power and Versatility of the For Loop in Programming

-
5
 m de lecture
-
for schleife

What is a "for loop"?

In programming, iterables are used to designate objects that group together a collection of objects that can be browsed. Iterables include lists, tuples, dictionaries and strings, to name but a few.

For loops are used to browse iterables and repeat a sequence of instructions for each element

The code to be executed is then repeated as many times as the number of elements contained in our iterable. As an essential part of programming, for loops are used in all data-related professions: data analysts, data scientists and data engineers.

In this article, we’ll look at how to use the ‘for’ statement on different types of object, and how for loops can be used to respond to the famous programming adage ‘Don’t Repeat Yourself’.

To familiarise ourselves with the use of loops, we will first learn how to use them on list items.

Using a loop to iterate through a list with the "For" instruction

We’re going to create a for loop to retrieve the first name of each student in a “students” variable of type list, which is made up of the first name and surname of the students. Then we add the first names to the “first_names” list.

Use Range to iterate :

The range function allows us to iterate over a sequence of numbers defined on a certain interval. Below, we display the value of each integer in the interval [0, 5[ (note that 0 is included but 5 is excluded).

By default, the range function takes 0 as the starting value, but it is also possible to change the starting value.

The range function can also be used to change the step between each value in the range:

Using the range function, it is also possible to iterate in the opposite direction, taking a negative step:

Using nested iterations

A nested iteration is a loop located inside another loop. The nested loop will be executed for each iteration of the loop above it.

In the example below, we iterate over each first name in the “first_names” list, which is of type string. Then, using a nested loop, we iterate over each letter of the first name and display the letter, its number and the number of the first name to which the letter belongs.

Rather than initiating a counter manually, we can use range to iterate over the number of elements in our iterable :

Use enumerate to benefit from an automatic element counter

Python has an enumerate() function which returns a tuple for each iteration, containing the index and the value of the iterable at that index.

Note that the output of the last three examples is the same, but the code of the last two solutions is more optimised.

Iterating on several iterables at the same time with Zip

You can use the built-in zip() function to iterate through several iterables at the same time. For each iteration, zip returns a tuple containing the elements located at the same position in each of the iterables.

Using the for loop and zip, we can create a “names” list containing the first and last names of each student.

Exit a loop with the Break instruction

It is possible to exit a loop if a particular condition is met by using “break”. As long as the condition is not verified, the loop is executed normally. As soon as the condition is true, the program exits the loop and moves on to the instruction after it.

A logical expression is used to check the condition. For example, above, we exit the loop if the type of an element in the list is not of type string. The loop was exited before displaying the element at index 2, which is of type int and not string.

Go to the next iteration by skipping the current iteration with the continue instruction

It is possible to skip the iteration you are in if a particular condition is met by using the python instruction “continue”. If the condition is true, the program will remain in the loop but will go directly to the next iteration.

We can see above that the loop has been executed except at index no.2, where the type of the element is int.

List Comprehensions

To simplify writing for loops on lists, you can use List Comprehensions, which make it easier to declare or modify list variables.

It is also possible to use nested List Comprehensions to create multi-dimensional lists.

The code above does in 1 line what the code below does in 6 lines.

We’ve just seen several uses for for loops on lists (and also strings). In the rest of this article, we’ll look at how to iterate over other types of object.

Iterate on a dictionary

An instruction can be repeated on a dictionary using the .items() method.

Python also supports the use of dictionary comprehensions called Dict Comprehensions :

Iterating on a Numpy Array

It is possible to iterate over the different dimensions of a Numpy array using for loops:

Using the nditer function and a loop, we can also access each element in our Numpy array directly.

Iterate on a Pandas dataframe

To iterate over each line of a Pandas dataframe, you can use iterrows.

A few words in conclusion

In this article, we have seen that for loops save precious time and optimise our code. We have seen how to use them, from a basic to an advanced level. To get to grips with this programming essential, don’t hesitate to practise and use them on different types of object.

For loops are used in all data-related professions. If you’re thinking of training for one of these professions, take a look at our various courses.

Facebook
Twitter
LinkedIn

DataScientest News

Sign up for our Newsletter to receive our guides, tutorials, events, and the latest news directly in your inbox.

You are not available?

Leave us your e-mail, so that we can send you your new articles when they are published!

Related articles

icon newsletter

DataNews

Get monthly insider insights from experts directly in your mailbox