Support Our Site

To ensure we can continue delivering content and maintaining a free platform for all users, we kindly request that you disable your adblocker. Your contribution greatly supports our site's growth and development.

How To Construct For Loops In Python

6 min read

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.

In this article, we will guide you through the construction of For loop in Python.

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:

for [Temporary variable] in [sequence]:
     [do something]

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,

for i in range(0, 4):
    print(i)

Output:

0
1
2
3

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 the 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,

for anything in range(0, 4):
    print(anything)

Output:

0
1
2
3

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

for anything in range(0,4):
     print("Hello")

Output:

Hello
Hello
Hello
Hello

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

For loop with strings

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

for letter in "Python":
    print(letter)

Output:

Python

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 behaviour by adding the end parameter in our print statement,

for letter in "Python":
    print(letter, end=" ")

Output:

P y t h o n

Now instead of printing letter 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:

my_list = [1,2,3,4]

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

 for num in my_list:
...    print(num)
...
1234

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 Tupple

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

my_tuple = ( 1,"some text", 234, "more text" )

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

 for i in my_tuple:
...    print(i)
...
1
some text
234
more text

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.

tup_list = [(1,2),(3,4),(4,5), (7,8) ]

This is essentially a list containing tuple pairs.

Obviously, we can iterate over the items and print the tuple pairs like this,

tup_list = [(1,2),(3,4),(4,5), (7,8) ] for item in tup_list:
...     print(item)
...
(1, 2)(3, 4)(4, 5)(7, 8)

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:

for (item1, item2) in tup_list:
    print(item1)
    print(item2)
    print('\n')

Output:

1
2
3
4
4
5
7
8

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.

user ={ 'name': 'Jhon' , 'email' :'[email protected]', 'pass' : 'somepass' }

Now try to iterate over the dictionary items,

>>> for item in user:
...    print(item)
...nameemailpass

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:

 >>> for item in user:
...     print(user[item])
...
[email protected]

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:

for [first iterating variable] in [outer loop]:
              # Outer loop
        [do something] # Optional
        for [second iterating variable] in [nested loop]:  # Nested loop
               [do something]

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 till the outer loop doesn't terminate.

Let's look at one example of nested loop in Python:

number = [1, 2, 3]
alphabets = ['a', 'b', 'c']

for num in number:
    print(num, end=" ")
    for letter in alphabets:
        print(letter, end=" ")

This will print the following output:

1 a b c 2 a b c 3 a b c

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.

Break statement terminates the loop immediately, we can introduce the break keyword with a conditional statement like if in our program.

list = [1,2,3,4,]
for i in list:
   if i == 3:
    break   print(i)

Output:

1
2

Adding break keyword to our loop resulted in the termination of the loop when i holds 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.

list = [1,2,3,4,]
for i in list:
   if i == 3:
    continue
   print(i)

Output:

124

In output 3 wasn't printed because of the continue statement. When i holds 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.

list = [1,2,3,4,]
for i in list:
   print(i)
else:
    print("Loop terminated")

Output

1
2
3
4
done

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 break.

Let's verify this theory with an example:

list = [1,2,3,4,]

for i in list:
   if i == 3:
    break
   print(i)
else:
    print("Done")

Output:

12

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


PYTHON

Latest Articles

Latest from djangocentral

How to Use Subquery() in Django With Practical Examples

In the realm of web development, Django stands as a powerful and versatile framework for building robust applications. One of the key aspects of developing efficient and optimized web applications is handling database queries effectively. In this article…
Read more →

4 min read

DRF Serializer: Handling OrderedDict and Converting It to a Dictionary or JSON

In Django Rest Framework (DRF) tests, when you access serializer.data, you might encounter an OrderedDict instead of a regular dictionary. This behavior is intentional and reflects the design of DRF's serialization process.Understanding the Problem The u…
Read more →

3 min read

Django Rest Framework CheetSheet: Mastering API Development

Django Rest Framework (DRF) is a powerful toolkit that makes building robust and scalable web APIs with Django a breeze. Whether you're a seasoned Django developer or a newcomer, having a comprehensive cheat sheet at your disposal can be a game-changer. …
Read more →

5 min read

How to Perform NOT Queries in Django ORM

In Django, performing NOT queries allows you to exclude certain records from the query results based on specific conditions. The NOT operator, represented by the tilde (~) when used in conjunction with the Django ORM's Q object, helps you construct compl…
Read more →

3 min read