While working in Python programming language, users may need to write and repeat the same block of code again and again. For example, they may need to display a particular message 50 times. It is a difficult and time-consuming approach to write the same message again and again. In this situation, they can utilize loops. Python has various looping/iterating functions i.e. “for”, “while”, and “do while” to execute the same code block a specific number of times. 

This guide will explain the “for” loop in Python.

Quick Outline

  1. What is For Loop in Python?
  2. How to Use For Loop in Python?

What is For Loop in Python?

The “for” loop is Python’s built-in iterating function that is utilized to iterate over a specific sequence i.e. list, dictionary, string, tuple, or a set. It executes all the items/elements of the iterable object in a sequence. 

Syntax

The syntax of the “for” loop is:

for <value> in <sequence>:
    <statements>

Here:

  • value” is the specific variable that iterates over the particular sequence.
  • sequence” is any iterator including a list, dictionary, string, tuple, etc.
  • statements” is the body of the “for” loop where users can perform different functions.

Flowchart

The below flowchart shows the working of the “for” loop in Python:

Flowchart of For Loop in Python

How to Use For Loop in Python?

To use the “for” loop in Python, users need to utilize its syntax and specify the desired iterator. The “for” loop can be used to iterate over strings, lists, sets, dictionaries, tuples, etc. Moreover, users can utilize it with the “range()” function, conditional statements, and control statements. 

Go through the provided use cases for a better understanding.

Case 1: Using For Loop to Iterate Over String, List, Tuple, Set, Dictionary

Strings, lists, tuples, sets, and dictionaries are iterables that can be looped/iterated over using the “for” loop. In the below examples, we have used the “for” loop to iterate over a string, list, tuple, set, and dictionary. 

Example 1: Iterate Over a String Using “for” Loop

In this example, we have defined a string named “my_string” with some characters. We have specified it in the “for” loop to iterate over its characters and print them:

my_string = 'Python'

for i in my_string:
  print(i)

The “for” loop has displayed all the characters of the string:

Example 2: Iterate Over the List Using “for” Loop

We have defined the “my_list” list with three items. We will use the “for” loop to iterate through this list and display each item in the sequence: 

my_list = ['Its', 'Linux', 'hint']

for i in my_list:
  print(i)

The below output displays the list’s items:

Example 3: Iterate Over Tuple Using “for” Loop

In this example, we have used the “for” loop with the “my_tuple” tuple to iterate through its elements:

my_tuple = ('Its', 0, 'Linux', 1, 'hint')

for i in my_tuple:
  print(i)

Subsequently, all the tuple items have been displayed:

Example 4: Iterate Over Set Using “for” Loop

Here, we have created a set named “my_set” with some elements. We are iterating through its elements using the “for” loop:

my_set = {1, 3, 5, 7}

for i in my_set:
    print(i)

The “for” loop has displayed all the set elements:

Example 5: Iterate Over the Dictionary Using “for” Loop

In this example, we have defined a “my_dictionary” dictionary with some keys and values. We are using the “for” loop with the “.items()” function to iterate through the dictionary items and display them in a sequence: 

my_dictionary =  {'US': 1, 'UK': 2, 'Canada': 3}

for i,j in my_dictionary.items():
  print(i,":",j)

Upon doing so, the dictionary items have been displayed in a sequence:

Case 2: Using For Loop With “range()” Function

The “range()” function is a built-in function that generates/returns a sequence of numbers within the given range. Sometimes, users may want to iterate over a loop till the specific iterable’s length. In this situation, the “range()” function can be used with the “len()” function in the “for” loop to calculate the length of the iterable and pass it as an argument to the “range()” function:

Here, we have a list named “my_list”. We are calculating the length of the list using the “len()” function and passing it as an argument to the “range()” function in the “for” loop: 

my_list = ['Its', 'Linux', 'hint']

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

The “for” loop has iterated over the list and printed all of its elements:

Users can also use the “range()” function with its different parameters, such as start, stop, and step in the “for” loop. Check out the provided examples for a practical demonstration.

Example 1: Using the “range()” Function With Stop Parameter in “for” Loop

In this example, we will specify the stop argument value “6” to the “range()” function in the “for” loop. This will iterate the loop six times and generate a sequence of numbers from 0 to 5:

for i in range(6):
  print(i)

The output can be seen in the screenshot below: 

Example 2: Using the “range()” Function With Start and Stop Parameters in “for” Loop

Here, we will use the “for” loop with the “range()” function by passing the start value “20” and the stop value “25” as arguments: 

for i in range(20, 25):
  print(i)

The “for” loop has been iterated five times and displayed the sequence of numbers from “20” to “24”:

Example 3: Using the “range()” Function With Start, Stop, and Step Parameters in “for” Loop

In this example, we are using the “range()” function with start value “1”, stop value “10” and step value “2” in the “for” loop. This will iterate the loop and generate the range from “1” to “9” with the increment of “2”:

for i in range(1, 10, 2):
  print(i)

Subsequently, the following output will be displayed:

Case 3: Using For Loop With Conditional Statements

The conditional statements are utilized to execute the desired block of code based on the specific conditions. Users can use conditional statements, such as “if-else” or “else” in the “for” loop to check various conditions and execute the specific code block accordingly. 

Example 1: Using “for” Loop With “if-else” Statement 

In this example, we have defined a “num” list with some integers and used it in the “for” loop to iterate over its elements. We have also used the “if-else” statements to check if the integer in the list is even or odd. If the integer is divisible by “2”, the “if” statement will be executed. Otherwise, the “else” statement will execute:

num = [6, 11, 23, 2, 9, 48]

for i in num:
    if i%2==0:
        print('Even Number')
    else:
        print('Odd Number')

The “for” loop has iterated over the list and displayed the results according to the specified “if-else” conditions:

Example 2: Using “for” Loop With “else” Statement 

Here, we are using the “for” loop with the “list1” list to iterate through its elements and print them. We have also the “else” block of code that will be executed after the “for” loop finishes executing:

list1 = [2, 7, 5, 11]

for i in list1:
    print(i)

else:
    print('Finished')

It can be observed that the “for” loop iterated through the list elements and displayed them. After that, the “else” block code is executed:

Case 4: Using For Loop With Control Statements

The control statements are utilized to change/modify the specific loop’s flow of execution. Users can stop the execution of the loop or skip iterations by using the control statements in the “for” loop. The control statements include “break”, “continue”, and “pass”. 

Example 1: Using “for” Loop With “break” Statement 

The “break” statement stops the loop’s execution and exits the loop when the specified condition is met. Here, we are using the “break” statement in the “for” loop to modify the loop’s execution. The “for” loop will iterate through the list and display the list items. When the list item is “Canada”, the “break” statement will stop the execution of the “for” loop, and the remaining list’s items after “Canada” will not be printed:

countries = ['US', 'UK', 'Canada', 'France', 'China']

for i in countries:
  print(i)

  if i == "Canada":
    break

It can be observed that the loop has been terminated at “Canada”:

If users want to terminate/exit the “for” loop when the list item is “Canada” but do not want to display it to the console, they can use the “print()” function after the “break” statement:

countries = ['US', 'UK', 'Canada', 'France', 'China']

for i in countries:
  if i == "Canada":
    break

  print(i)

By doing so, the loop has been terminated when the specified condition is met:

Example 2: Using “for” Loop With “continue” Statement 

The “continue” statement skips the loop’s execution when the specific condition is met. It stops/skips the loop’s current iteration and continues with the next element. Here, we have a “countries” list and we have specified it in the “for” loop to iterate through it. We have also used the “continue” conditional statement. When the list item is “Canada”, the loop will stop/skip the execution at it and continue to the next item:

countries = ['US', 'UK', 'Canada', 'France', 'China']

for i in countries:
  if i == "Canada":
    continue

  print(i)

It can be seen that the “Canada” list item has been skipped and other elements have been displayed:

Example 3: Using “for” Loop With “pass” Statement 

The “pass” statement is utilized as a null statement or as a placeholder for the code that needs to be added later. When users use the “for” loop without any function in the body, it gives an error as seen below:

To avoid this error, use the “pass” statement. This will indicate that there is no code in the loop to execute:

string1 = 'Python'

for x in string1:
  pass

By doing so, the code has been executed without any error:

Case 5: Using Nested For Loop

The nested “for” loop is a loop inside another “for” loop. Users can use one “for” loop within another “for” loop. The inner loop’s iteration executes every once for every outer loop iteration. 

For example, we have defined two lists i.e. “ranks” and “countries”. We have specified the “ranks” list in the outer “for” loop and the “countries” list in the “inner” “for” loop. The nested “for” loop will print all the elements of the “ranks” list one by one with the “countries” list’s elements:

ranks = [1, 2]
countries = ['US', 'Canada', 'France']

for i in ranks:
  for j in countries:
    print(i, j)

The output of the nested “for” loop can be seen in the screenshot below:

Conclusion

In Python, the “for” loop is a built-in iterating function that iterates over a particular sequence. It executes all the iterable object’s elements in a series. The “for” loop can be utilized to iterate over iterables including strings, lists, sets, dictionaries, tuples, etc. Moreover, users can also use it with the “range()” function, conditional statements, control statements, and within another “for” loop. This guide has efficiently explained the “for” loop in Python.