In this article, you will learn how to construct For Loops In Python. Before we get started, if you want Conditional Statements in Python, please go through the following article: Conditional Statements in Python.

Many objects in Python are iterable which means we can iterate over the elements of the object. Such as every element of a list or every character of a string. Loops facilitate programmers to iterate over a block of code at every iteration, in Python we can iterate over objects with either While loop or For loop.

For Loop In Python

A for loop implements the repeated execution of code based on a loop counter or the loop variable. For loops are used when the number of iterations is known in advance. This is the structure of a basic for loop in Python:

The syntax is very specific therefore you should always follow this particular layout. The for loop must have a colon(:) after the sequence, and the statement under the loop must be indented. Python relies on indentation to know which block of code belongs to the for loop. Always indent your code by adding 4 spaces to the write of the statement. Let’s begin by creating a very basic for loop,

Output:

In the above example, we set i as the temporary iterable variable and printed its value in each iteration.

If you are not already aware of the range() keyword, it’s one of Python’s built-in immutable sequence types. In loops range() can be used to control the number of iterations. We can pass the following 3 arguments to the range method, START, STOP, and STEPS. In the above example, we passed the starting and ending values i.e. 0 and 4.

We can assign literally anything we wish as the iterable variable, and it will work,

Output:

It’s not mandatory to reference the temporary iterable variable in the loop body. We can print a simple “Hello” String in each iteration.

Output:

Now that we know the basics let’s go ahead and explore loops with different object types.

For loop with strings

We can iterate over the characters of a string like this,

Output:

In the above example, we iterated over the letters of the word “Python” and printed them. However it doesn’t look appealing because the output is spread over multiple lines, we can change this behavior by adding the end parameter in our print statement,

Output:

Now instead of printing letters in a new line, our result prints out in a single line with space in between letters.

For loops in Lists

Iteration over the item of a list is also possible to do so first, create a basic list of numbers and store it in the variable my_list:

Now, we can iterate over the items of the list and print them.

As a reminder, you can name your iterable variable anything you want, but it advised to name it something which is related to the actual variable.

For loops In Tuple

For loop works pretty much exactly like the list. Let’s create a tuple and store it in the variable my_tuple.

We can iterate over the items of the tuple just like we did in lists,

There is something we can do with tuples and for loop which is called tuple unpacking.

Tuple unpacking In Python

Create a list of tuples and store it in the variable tup_list.

This is essentially a list containing tuple pairs. Obviously, we can iterate over the items and print the tuple pairs like this,

In Python, we can do something called tuple unpacking to get the items inside the tuples printed. For doing so we need to bring two iterable variables in the for loop:

Output:

Finally, the items of tuple got unpacked, this is something which you will use a lot in your programs. However, this will work only when you have a list of tuples.

For loops in Dictionary

When iterating through a dictionary, it’s important to keep the key : value structure in mind to ensure that you are calling the correct element of the dictionary. Let’s create a basic dictionary and store it in a variable dictionary.

Now try to iterate over the dictionary items,

But we are only gettings the keys, not the values. When using dictionaries with for loops, the iterating variable corresponds to the keys of the dictionary, and dictionary_variable[iterating_variable] corresponds to the values. To print the values of our dictionary do the following:

Nested For Loops

Nested loops are nothing but loops inside a loop. You can create any number of loops inside a loop. Roughly a nested loop structure looks similar to this:

The program will first trigger the outer loop which after it’s the first iteration will trigger the inner loop which will run till it’s compilation then return back to the outer loop which will trigger the second iteration of the outer for loop. This process will continue until the outer loop doesn’t terminate. Let’s look at one example of a nested loop in Python:

This will print the following output:

The numbers are getting printed before the letters because the outer loop is printing them.

Break and Continue Keyword

Python provides two keywords to terminate a loop prematurely, they are Break and Continue. The break statement terminates the loop immediately, we can introduce the break keyword with a conditional statement like if in our program.

Output:

Adding the break keyword to our loop resulted in the termination of the loop when I hold the value 3. The continue statement doesn’t break the entire loop it just terminates the current iteration. As soon as our interpreter hits the continue statement it goes straight to the top of the loop instead of executing loop statements for that iteration.

Output:

Output 3 wasn’t printed because of the continued statement. When i hold the value 3 Python goes back to the beginning of the loop instead of printing it.

Else Clause In Python

Python provides an unique else clause to for loop to add additional statements when the loop is terminated.

Output

You might be wondering you can do this with a normal print statement too indeed you can. Actually, the else clause only gets executed when the for loop terminates by itself and not by any explicit keyword like a break. Let’s verify this theory with an example:

Output:

Else clause won’t get executed because the loop didn’t terminate naturally, it was forced to terminate by the break keyword.

How To Construct For Loops In Python

The article was published on September 27, 2020 @ 1:05 PM

Leave a Comment