Python

Python for Loop

In this article, we’ll dive deep into one of the most fundamental constructs in programming – the for loop. Specifically, we’ll focus on the Python for loop, exploring its syntax, flow diagram, execution order, and various use cases. We’ll also compare the Python for loop with the while loop to help you understand when to use each. So, let’s get started! 

Table of Contents
Watch Now High-Definition Instructional Video: Python for Loop

Python loops allow for the repetitive execution of a block of code, with two primary types: for loops, which iterate over sequences such as lists or strings, and while loops, which continue as long as a certain condition is met.

What is for Loop in Python? 

for loop is a control structure that allows you to iterate over a sequence (like lists, strings, tuples, or dictionaries) and execute a code block for each element in the sequence. In Python, for loops use the for keyword, followed by a user-defined variable that represents the current element in the sequence. 

Example 

# A list of fruits 
fruits = ["apple", "banana", "cherry"]  

# Loop through each fruit in the list 
for fruit in fruits:  
    print(fruit)  

The output will be: 

apple 
banana 
Cherry

In the above example, the for loop iterates over the fruits list. With each iteration, the variable fruit takes on the value of the current element in the list, and the print() function prints the value of fruit.  

The execution order would be: 

  1. Create an iterator for the fruits list. 
  2. Check if there is a next element in fruits. In this case, there is (apple). 
  3. Assign the next element (apple) to the loop variable fruit
  4. Execute the loop body, which prints the value of fruit
  5. Go back to step 2, check for the next element (banana), and repeat the process. 
  6. After all elements have been processed, the loop terminates, and the program continues executing any code after the loop. 

Python for Loop Flow Diagram  

The flow of a Python for loop can be illustrated with the following diagram: 

C# for Loop Flowchart
  1. Initialize the loop variable with the first element in the sequence. 
  2. Check if there are more elements in the sequence. 
  3. If there are no more elements, exit the loop. 
  4. Execute the loop body. 
  5. Move on to the next element in the sequence and repeat from step 2

Python for Loop Syntax 

In Python, a for loop is used for iterating over a sequence (such as a list, tuple, or string). The general syntax for a Python for loop is as follows: 

Python for Loop Syntax

Syntax 

for item in sequence:  
    # Code to be executed

Here’s a brief explanation of each part of the syntax: 

  1. for: The keyword used to start a for loop
  2. item: A temporary loop variable that is used to store the current element in the sequence for each iteration of the loop. 
  3. in: The keyword used to specify the sequence that you want to iterate over. 
  4. sequence: The actual sequence (e.g., list, tuple, or string) that you want to iterate over. 
  5. ) A colon is used to mark the end of the for loop declaration and the beginning of the loop body. 
  6. The indented code block (lines below the colon) represents the code to execute during each iteration of the loop. 

Python for Loop Execution Order  

In Python, a for loop follows a specific execution order. Here’s a step-by-step breakdown of the process: 

Python for Loop Execution Order
  1. Initialization: This is where you declare the iterator or sequence you will be iterating over. This can be any iterable object such as a list, string, tuple, dictionary, etc. This initialization happens only once when the loop first starts. 
  2. Pass Value:  The interpreter passes the next value from the iterator to the item variable. The first value in the sequence is used in the first run. In each subsequent iteration, the next value from the sequence is assigned. 
  3. Body Execution: The interpreter then executes the body of the loop using the current value of the item variable. 
  4. Repeat: Once the body has finished executing, the interpreter checks if there are more elements in the sequence. If there are, it goes back to step 2. If not, it ends the loop. This continues until there are no more elements in the sequence. 

Remember, Python’s for loop doesn’t use an index counter like some other programming languages; it uses an iterator to loop over elements of any sequence (e.g., list or string) in the order they appear in the sequence.  


Python for Loop with else Clause  

An optional else clause can be added after a for loop. The code inside the else block will be executed once the loop has finished iterating through the sequence, but only if the loop was not terminated by a break statement. 

The syntax for a for loop with an else clause is as follows: 

Python for Loop with else Clause

Syntax 

for item in sequence: 
    # statements to be executed inside the loop 
else: 
    # statements to be executed after the loop completes all iterations

Here, item is a variable that takes on the values of each element in sequence, which can be a list, tuple, string, or any iterable object. The statements inside the loop block are executed for each element in the sequence. If the loop completes all iterations without encountering a break statement, then the statements inside the else block are executed.  

Here is an example to demonstrate the use of the else clause in a for loop

Example 

fruits = ['apple', 'banana', 'cherry'] 

for fruit in fruits: 
    print(fruit) 
else: 
    print("No more fruits left")

In this example, the for loop iterates over the list of fruits. The print statement inside the loop will print each fruit in the list. After the loop completes, the else clause is executed, and it prints “No more fruits left” because no break statement was encountered during the loop.  

Output:

apple 
banana 
cherry 
No more fruits left

Note that the else clause is executed only when the loop completes normally without a break statement. If a break statement is encountered, the else clause is skipped. 


Python for Loop with break Statement  

The break statement is used to exit a for loop prematurely before all elements in the sequence have been processed. When a break statement is encountered, the loop stops immediately, and the program executes the code after the loop. 

Here’s the syntax for using a break statement inside a for loop with if condition:  

Python for Loop with break Statement

Syntax

for item in sequence: 

    # code to execute 
    if condition: 
       break 

    # more code to execute

Here, item represents the loop variable, sequence is the object to be iterated, and condition is a Boolean expression that, when evaluated to True, will cause the loop to terminate. 

Here’s an example of how to use a for loop with a break statement: 

Example 

fruits = ["apple", "banana", "cherry", "orange", "kiwi"] 

# Target fruit to search for 
target = "orange" 

for fruit in fruits: 
    print(fruit) 

    # If the current fruit is equal to the target, break the loop 
    if fruit == target: 
        break 

In this example, the for loop iterates over the list of fruits. The print statement inside the loop will print each fruit in the list. When the loop encounters the if statement, it checks if the current fruit is equal to the target fruit (orange in this case). If it is, the break statement is executed, which terminates the loop early. 

As a result, the output of the code will be: 

apple 
banana 
cherry 
orange

Note that the loop stops after orange is printed, and kiwi is not printed since the loop terminated early with the break statement. 


Python for Loop with continue Statement  

The continue statement is used to skip the remaining code inside the loop for the current iteration and move on to the next element in the sequence. This is useful when you want to skip certain elements without exiting the loop entirely. 

It’s commonly used in for loops and while loops. Here’s the syntax for using the continue statement in a for loop

Python for Loop with continue Statement

Syntax

for item in sequence: 

    # some code here 
    if condition: 
       Continue 

    # more code here that will be skipped if continue statement is executed

Example 

fruits = ["apple", "banana", "cherry", "orange", "kiwi"] 

for fruit in fruits: 

    # If the current fruit is equal to the orange, skip iteration 
    if fruit == "orange": 
        continue 

    print(fruit)

In the above example, the for loop iterates over the list of fruits. The print function inside the loop will print each fruit in the list. The if statement checks if the current fruit is orange. If it is, the continue statement is executed, which skips the current iteration and moves on to the next iteration. 

As a result, the output of the code will be: 

apple 
banana 
cherry 
kiwi

Note that orange is not printed because the continue statement skips that iteration of the loop. 


Python for Loop with pass Statement  

The pass statement is a null operation, meaning it does nothing when executed. It can be used as a placeholder in code where a statement is syntactically required, but no action needs to be taken. The loop will simply iterate through the sequence without performing any actions. 

Here’s an example: 

Example 1 

for fruit in fruits:  

    if fruit == "orange":  
        pass  
    else:  
        print(fruit)

Inside the for loop, there’s an if statement that checks if the current fruit is an orange. If the current fruit is indeed orange, it executes the pass statement, which effectively does nothing and moves on to the next iteration. 

However, if the current fruit is not an orange, the else clause gets triggered, and the program prints the name of the fruit. 

The above code will print out all the fruits in the list fruits except for orang. If orange appears in the list, it will be skipped and not printed due to the pass statement. 

As a result, the output of the code will be: 

apple 
banana 
cherry 
Kiwi

Here’s another example where pass can be useful. Let’s say we want to create a for loop that will eventually do something with even numbers and something else with odd numbers, but we haven’t yet decided what to do with the even numbers. We can use pass to act as a placeholder: 

Example 2

for i in range(10):  
 
    if i % 2 == 0:  # If the number is even  
        pass        # We will do something here later  
    else:           # If the number is odd  
        print(i)    # We print the number

In the above example, odd numbers will be printed, but even numbers won’t do anything yet because of the pass statement. Once we decide what we want to do with the even numbers, we can replace pass with the appropriate code. 

Output:





9


Python for Loop with range() Function  

The range() function in Python is a built-in function that generates a sequence of numbers, which can be used in combination with a for loop to iterate over a specified range of values. It is widely used in Python to control the number of times a loop should be executed. 

The range() function has three arguments: 

  1. range(stop)                       Generates a range from 0 to stop-1 
  2. range(start, stop)            Generates a range from start to stop-1 
  3. range(start, stop, step)  Generates a range from start to stop-1 with a custom step 

Here are examples of using the range() function with one, two and three arguments: 

range(stop) 

Generates a sequence of numbers from 0 up to, but not including the stop argument. 

Example 

for i in range(5): 
    print(i)
This will output:





4

range(start, stop) 

Generates a sequence of numbers from the start argument up to, but not including the stop argument. 

Example 

for i in range(2, 7): 
    print(i)
This will output:





6

 range(start, stop, step) 

Generates a sequence of numbers from the start argument up to, but not including, the stop argument, incrementing by step

Example 

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





9

 In these examples, the range() function generates a sequence of numbers based on the provided arguments and the for loop iterates over each number in the sequence. 


Python Nested for Loops  

Python Nested for Loops allows you to iterate over multiple sequences or nested data structures like lists, tuples, and dictionaries by using nested for loops inside each other. You can have a for loop inside another for loop. This is called a nested for loop. The outer loop runs first, and the inner loop runs completely for each iteration of the outer loop. 

The syntax for the nested for loops in Python is as follows: 

Python Nested for Loop

Syntax

for item1 in sequence1: 
    # Outer loop body  
    for item2 in sequence2: 
        # Inner loop body

Here, the item1 and itemare loop variables, and sequence1 and sequence2 are the sequences over which the loops are iterating. The code block inside the nested loop is executed for each combination of values of the variables itemand item2

You can use a nested loop as follows: 

Example 1

for i in range(1, 4): 
    for j in range(1, 4): 
        print(i, j)

In this example, the outer loop iterates over the values 1, 2, and 3. For each value of i, the inner loop iterates over the values 1, 2, and 3 as well. The print statement inside the inner loop prints the values of both and j. As a result, the output of the code will be: 

Output:

1 1 
1 2 
1 3 
2 1 
2 2 
2 3 
3 1 
3 2 
3 3

Nested loops can have more than two levels: 

Example 2 

for i in range(2):  
    for j in range(2):  
        for k in range(2):  
            print(f"({i}, {j}, {k})")

This example demonstrates a three-level nested loop, which prints all possible combinations of indices (ijk). 

Output:

(0, 0, 0) 
(0, 0, 1) 
(0, 1, 0) 
(0, 1, 1) 
(1, 0, 0) 
(1, 0, 1) 
(1, 1, 0) 
(1, 1, 1)

Use cases: 

Nested loops are commonly used in various scenarios, such as: 

  • Iterating over multi-dimensional arrays or matrices 
  • Generating combinations or permutations 
  • Running simulations with multiple parameters 
  • Implementing algorithms that require nested iterations, such as sorting or searching algorithms. 

Nested loops can be nested inside other loops to any depth. However, nesting can become computationally expensive as the number of levels or iterations increases, which may result in slow execution times. It’s essential to evaluate the efficiency of your code and optimize it when necessary. 


Python Infinite for Loop  

An infinite for loop is a loop that never ends. Although it’s rare to create an infinite for loop intentionally, it’s important to understand how it can happen accidentally. An infinite for loop can be created using an iterator that never terminates or incorrectly using a break statement.  

You can create an infinite for loop by omitting the sequence or range that the loop should iterate over. Here’s an example of an infinite for loop

Example 1 

# WARNING: This is an example of an infinite loop. Do not run this code as-is.  
for i in []: 
    print(i)

In this example, an empty list is passed to the for loop, which means there are no elements to iterate over. As a result, the loop will not execute and will terminate immediately. 

However, if you omit the sequence or range argument altogether, the loop will continue to execute indefinitely: 

Example 2

for i in range(): 
    print(i)

This will result in an error because range() function requires at least one argument.  

It’s important to avoid creating infinite loops, as they can consume many resources and cause your program to hang or crash. If you find yourself in an infinite loop, you can stop the program by interrupting the execution with a keyboard interrupt (Ctrl + C on most platforms).  


Looping through Dictionary  

Looping through a dictionary in Python using a for loop is a common operation. A dictionary is an unordered collection of key-value pairs, where each key is unique. You can loop through a dictionary in several ways, such as looping through its keys, values, or key-value pairs (items). Here’s a detailed explanation of each method: 

Looping through keys 

You can loop through the keys of a dictionary using the for loop and the keys() method, although this method is not required as a dictionary is iterable by default on its keys. 

Example 1 

fruits = {"apple": 3, "banana": 2, "cherry": 5}  

# Looping through keys  
for key in fruits.keys(): 
    print(key)

You can also loop through the keys without using the keys() method: 

for key in fruits:  
    print(key)
Output: 

apple 
banana 
cherry

 Looping through values 

To loop through the values of a dictionary, you can use the values() method along with the for loop

Example 2

# Looping through values  
for value in fruits.values():  
    print(value)
Output: 



5

Looping through key-value pairs (items)

To loop through both keys and values simultaneously, you can use the items() method, which returns a view object that displays a list of the dictionary’s key-value tuple pairs. 

Example 3 

# Looping through key-value pairs  
for key, value in fruits.items():  
    print(f"{key}: {value}")

In the above example, the items() method returns the key-value pairs as tuples, and the for loop unpacks each tuple into key and value variables on each iteration. 

Let me explain this again, the for loop iterates over each key-value pair in the fruits dictionary. For each iteration of the loop, the current key and value of the dictionary are assigned to the variable’s key and value, respectively. The print statement inside the loop prints the values of key and value. As a result, the output of the code will be: 

Output: 

apple: 3 
banana: 2 
cherry: 5

Note that you can have a dictionary with any data type as the value, and the for loop will work the same way. The for loop will iterate over each key-value pair in the dictionary, regardless of the data type of the value, and perform the operation for each pair. 


Looping through list  

for loop can be used to iterate through elements in a list. The loop will execute the code block for each element in the list. 

Example 1 

fruits = ["apple", "banana", "cherry"]  

for fruit in fruits:  
    print(fruit)

In this example, the for loop iterates over each element in the fruits list. For each iteration of the loop, the current element of the list is assigned to the variable fruit. The print statement inside the loop prints the value of fruit. As a result, the output of the code will be: 

Output: 

apple 
banana 
cherry

 You can also use the range() function to iterate over the indices of a list and access each element using the index. Here’s an example: 

Example 2  

fruits = ["apple", "banana", "cherry"]  

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

In this example, the range() function generates a sequence of integers from 0 to the length of the fruits list minus 1. For each iteration of the loop, the current index is assigned to the variable i. The print statement inside the loop prints the element of the fruits list at the current index. The len() function returns the length of the fruits list. As a result, the output of the code will be: 

Output: 

apple 
banana 
cherry

Both approaches will achieve the same result, but using the for loop directly with the list is generally more readable and simpler to use. 


Looping through tuple  

In Python, a tuple is a collection of elements, just like a list. The difference is that a tuple is immutable, meaning its values cannot be changed after it is created. You can use a for loop to iterate over each element in a tuple and perform some operation for each element. 

Here’s an example: 

Example 1

my_tuple = (1, 2, 3, "apple", "banana", "cherry") 

for item in my_tuple: 
    print(item)

In this example, the for loop iterates over each element in the my_tuple tuple. For each iteration of the loop, the current element of the tuple is assigned to the variable item. The print statement inside the loop prints the value of item. As a result, the output of the code will be: 

Output: 




apple 
banana 
cherry

Note that you can have a tuple of any data type and the for loop will work the same way. The for loop will iterate over each element in the tuple, regardless of its data type, and perform the operation for each element. However, since tuples are immutable, you cannot modify their values inside the loop. 

Here’s another example that demonstrates some of the differences between looping through a tuple and looping through a list: 

Example 2

my_tuple = (1, 2, 3, "apple", "banana", "cherry") 

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

In this example, we use the range() function to create a sequence of indices from 0 to 4 (the length of the tuple minus one). Inside the loop, we access each element in the tuple using its index. Notice that we need to use square brackets to access elements of a tuple, just like with lists. 

When you run this code, the output will be the same as the previous example: 

Output: 




apple 
banana 
cherry


 Looping through string   

for loop can be used to iterate through the characters in a string. The loop will execute the code block for each character in the string. 

Example 1 

text = "Python"  
for char in text:  
    print(char)

In this example, the for loop iterates over each character in the text string. For each iteration of the loop, the current character of the string is assigned to the variable char. The print statement inside the loop prints the value of char. As a result, the output of the code will be: 

Output: 






n

Note that you can also use indexing to access individual characters of a string, just like with lists. For example: 

Example 2 

text = "Python"   

print(text[0]) # Output: "P" 
print(text[3]) # Output: "h"

In this example, we use indexing to access the first character and the fourth character of the text string. 


Python for Loop vs while Loop  

Both for and while loops are used for iteration in Python, but they have some differences in terms of their usage and syntax. 

for Loop 

  • for loop is used to iterate over a sequence, such as a list, tuple, or string. 
  • It executes a fixed number of times based on the length of the sequence. 
  • The loop variable takes on each value in the sequence, one at a time, and the block of code inside the loop is executed for each value. 
  • It is commonly used when you know the number of iterations needed. 

Syntax: for variable in sequence:  

Example: for i in range(5): 

while Loop

  • while loop is used to repeatedly execute a block of code as long as a certain condition is true. 
  • It executes an indefinite number of times, depending on the condition. 
  • The condition is checked at the beginning of each iteration, and if it is true, the block of code inside the loop is executed. 
  • It is commonly used when you do not know the number of iterations needed or when you want to iterate until a certain condition is met. 
  • It can be used to create an infinite loop if the condition is always true, so it’s important to include a way to break out of the loop. 

Syntax: while condition: 

Example: while i < 5: 

Comparing for and while loops: 

# Using a for loop  
for i in range(5):  
    print(i)  

# Using a while loop  
i = 0  
 
while i < 5:  
    print(i)  
    i += 1

In both examples, the output will be: 





4

As you can see, both for and while loops can be used to accomplish similar tasks, but their syntax and use cases differ. Use a for loop when you know the number of iterations or when you want to iterate over a sequence, and use a while loop when you want to continue looping as long as a certain condition remains true


Conclusion 

 In this comprehensive guide, we covered various aspects of the Python for loop, from its syntax and flow diagram to its execution order and use cases. We also demonstrated how to use the for loop with various control statements (breakcontinuepass, and else), the range() function, and nested loops. Furthermore, we discussed how to use the for loop to iterate through different data structures like dictionariesliststuples, and strings. Finally, we compared the for loop with the while loop to help you understand when to use each.