For enquiries call:

Phone

+1-469-442-0620

Aage ki Socho

HomeBlogProgrammingPython for Loop Explained With Examples

Python for Loop Explained With Examples

Published
05th Sep, 2023
Views
view count loader
Read it in
16 Mins
In this article
    Python for Loop Explained With Examples

    In programming, you often need to repeat actions. The for loop in Python is a powerful control flow statement that enables you to process data, automate repetitive tasks, and perform operations on each member in a collection. It enables you to repeatedly iterate over a sequence of elements, including strings, lists, and even custom objects.

    In this tutorial, you will learn about the various aspects of using for loop in Python. From gaining a solid understanding of its basic functionality and syntax to exploring advanced techniques like nested for loops and reversed for loops, this tutorial will equip you with the knowledge and skills necessary to utilize the power of for loops in your Python programs effectively.

    If you are interested in Python programming, you can check out the Python Programming classes offered by KnowledgeHut. It provides comprehensive training to enhance your Python programming skills and gain certification in the field

    What Is for Loop in Python? 

    Unlike languages like C and Java, Python does not implement the three-expression loop. Instead, Python focuses on collection-based iteration, where the loop iterates over a collection of objects rather than relying on specifying numeric values or conditions. 

    The general for loop in Python syntax is as follows:

    for item in iterable:
    # code block to be executed

    In the above syntax, the "iterable" refers to a collection of objects, such as a list, tuple, or string. The code block to be executed within the loop is indented and runs once for each item in the iterable. During each iteration, the loop variable, named "item" here, represents the current element from the iterable. The loop variable is updated with the value of the next element in the iterable in each iteration. Thus it allows you to perform specific operations or actions on each item separately.

    Unlike some other languages, you also don’t have a for each loop in Python. The for loop in Python itself works like the for each loop. If you’re looking to explore different programming languages, you can consider enrolling in the Best Programming Courses offered by KnowledgeHut.

    Why Use for Loop? 

    There are two types of loop- for loop and while loop in Python. These loops serve different purposes and offer distinct advantages based on the specific requirements of your code. 

    As discussed earlier, the for loop is used to iterate over a sequence. On the other hand, the while loop continues iterating until a specified condition becomes false.

    Here are some reasons why you would prefer for loop over while loop:

    1. When the number of iterations is predetermined or known in advance, a for loop is a better choice. It allows you to specify the range or collection to iterate over, providing a clear indication of how many times the loop will run. This is especially beneficial when you need to repeat a set of instructions for a fixed number of times.
    2. for loops provide a more concise and readable syntax, especially when compared to a while loop with an index variable and a conditional expression. The loop variable in a for loop directly represents the current element from the collection, eliminating the need for additional control variables and simplifying the code structure.
    3. The for loop in Python provides additional features like the ability to iterate over multiple iterables simultaneously using the zip() function or to access both the index and element using the enumerate() function. These features enable more flexible and efficient iteration patterns, making for loops the preferred choice in such scenarios.

    How for Loop Works? 

    The for loop in Python follows a specific flow of execution, which can be represented using the following flow chart:

    This flowchart visually demonstrates how a for loop works in Python. Let’s understand each of the steps involved:

    1. Before the loop starts, the loop variable is set to the first element in the iterable. This step is handled automatically by the for loop itself.
    2. The loop then checks a test condition to verify if there are more elements in the iterable before each iteration. If the test condition is false, i.e., there are no more elements in the iterable, the loop terminates and execution continues outside the loop.
    3. If the test condition is true, the loop body is executed. The loop body consists of the indented code block that performs the desired operations or actions on the current element of the iterable. 
    4. After executing the loop body, the loop variable is updated to the next element in the iterable automatically by the for loop. This step allows the loop to process each element in the iterable one by one.

    The loop continues to repeat steps 2-4 until all elements in the iterable have been processed. For each iteration, the loop variable takes on the value of the next element in the iterable, and the loop body is executed accordingly. Once all elements in the iterable have been processed, the loop terminates, and the program continues with the next line of code after the loop.

    Here's an example that shows the usage of for loop in Python:

    numbers = [1, 2, 3, 4, 5]
    
    for num in numbers:
    print(num)

    Output:

    1
    2
    3
    4
    5
    
    

    In the above for loop in Python program, the loop iterates over each element in the "numbers" list. The loop variable "num" takes on the value of each element in the list, and the print statement inside the loop prints the value of "num" for each iteration.

    For Loop With range()

    You can also use the for loop in Python with range function to iterate over a sequence of numbers. The range() function generates a sequence of numbers based on the specified start, stop, and step values. When combined with a for loop, it allows you to perform a certain task a specific number of times or iterate over a range of values.

    The syntax for using a for loop with range is as follows:

    for variable in range(start, stop, step):
    # code block to be executed

    The range function generates a sequence of numbers starting from the "start" value and ending before the "stop" value. If not specified, the default "start" value is 0, and the default "step" value is 1. In the first iteration, the loop variable holds the value of the start number, and in subsequent iterations, it updates to the next value in the sequence.

    Here's an example that demonstrates the use of a for loop in Python with range function to print numbers from 1 to 5:

    for num in range(1, 6):
    print(num)

    Output:

    1
    2
    3
    4
    5

    Note: The range function generates the sequence of numbers from start to end-1 (inclusive).

    Loop Control Statements in for Loop 

    The for loop in Python comes with a number of loop control statements that give the user more flexibility to change the normal flow of the loop's execution. You use these control statements when you want to exit the loop or skip a part of the loop based on a condition. 

    Let's explore three important loop control statements in the context of a for loop: break, continue, and pass.

    Break Statement

    The break statement is used to prematurely terminate the execution of a loop. The loop immediately exits when a break statement is encountered in the loop body, and the program moves on to the line of code after the loop. The statement is useful when you want to end the loop iteration early based on specific conditions.

    The flow chart for the break statement is as follows:

    Based on the above flow chart, the execution of a loop with a break statement follows the below steps:

    1. The loop begins.
    2. If the condition is evaluated as true, the loop body is executed.
    3. If the loop body contains a break statement, the control immediately exits the loop and proceeds to Step 6.
    4. After executing the loop body, the control moves to the next iteration in Step 4.
    5. If the condition is evaluated as false, the control exits the loop and moves to Step 6.
    6. The loop terminates.

    Here's a for loop in Python example that demonstrates the usage of the break statement:

    nums = [1, 3, 5, 16, -7, 9, 7]
    for num in nums:
    if num < 0:
    print("I found a break statement! Exiting the loop...")
    break
    print("Would I be printed?")
    print(num)
    print("Outside loop!")
    
    

    Output:

    1 
    3 
    5 
    16 
    I found a break statement! Exiting the loop... 
    Outside loop! 
    

    In this example, the loop iterates normally through the elements of the list until it reaches the number 16. It enters the if condition as soon as it finds a number less than zero, in this case, -7. Inside the if condition, first, it prints the message and then encounters a break statement. The second print statement inside the if the condition is not printed because the break statement causes it to exit the loop. Finally, it executes the last print statement.

    Continue Statement

    The continue statement is used to skip the remaining code within a loop iteration and move on to the next iteration. When a continue statement is encountered, the loop jumps to the next iteration without executing any code below the continue statement. This is useful when you want to skip specific iterations based on certain conditions but continue with the loop execution.

    The flow chart for the continue statement is as follows:

    Based on the above flow chart, the execution of a loop with a continue statement follows the below steps:

    1. The loop starts.
    2. If the condition is evaluated as true, the control enters the loop. If a continue statement is encountered, the control proceeds to Step 4 and starts the next iteration.
    3. The loop body is executed.
    4. After the loop body execution, if a continue statement is present or the loop execution inside the body is complete, the control moves to the next iteration in Step 4.
    5. If the loop execution is completed or the loop condition becomes false, the control exits the loop and moves to Step 7.
    6. If the loop condition is evaluated as false, the control exits the loop and proceeds to Step 7.
    7. The loop terminates.

    Here's a for loop in Python example that demonstrates the usage of the continue statement:

    nums = [1, 3, 5, 16, -7, 9, 7]
    for num in nums:
    if num < 0:
    print("I found a continue statement!")
    continue
    print("I would be skipped!")
    print(num)

    Output:

    1
    3
    5
    16
    I found a continue statement!
    9
    7

    In the above code, as soon as the control reaches -7, it enters the if condition where it first prints the print statement. Then it finds the continue statement which tells it to skip the code below it and move to the next iteration. Hence -7 will never be printed.

    Pass Statement

    When no action is necessary, the pass statement is used as a placeholder within a loop. It is a null operation that has no effect. It is often used to define empty loops that will be filled later or as a temporary placeholder to prevent syntax issues when working on unfinished code. The pass statement allows the loop to continue without any action.

    Here's a for loop in Python example that demonstrates the usage of the pass statement:

    nums = [1, 3, 5, 16, -7, 9, 7]
    for num in nums:
    if num < 0:
    print("I found a pass statement!")
    pass
    print(num)

    Output:

    1
    3
    5
    16
    I found a pass statement!
    -7
    9
    7

    In the above example when the loop finds a number less than zero, i.e. -7 in this case, the print statement is executed. After printing, the loop continues, and the number -7 is printed. Thus, you can see the pass statement didn’t affect the execution flow of the loop. 

    Else Block in Loop 

    The for loop in Python allows you to use an else statement within it. When a for loop finishes its iterations normally, that is, without encountering a break expression, the else block is performed. Note that the else block is optional in the for loop. The else block in a loop will not be executed when the loop ends due to a break statement.

    Here’s an example that demonstrates the normal flow of the else block in a for loop:

    nums = [1, 3, 5, 16, -7, 9, 7]
    for num in nums:
    print(num)
    else:
    print("Done!")

    Output:

    1 
    3 
    5 
    16 
    -7 
    9 
    7Done! 
    

    As mentioned, the loop executes normally in the above example. Then control flows to the else block, and the print statement is executed.

    Let’s see another example where the loop encounters a break statement:

    nums = [1, 3, 5, 16, -7, 9, 7]
    for num in nums:
    if num < 0:
    break
    else:
    print("Done!")

    In the above example, when the loop finds a number less than zero, i.e. -7, the break statement is executed. Since the loop is terminated using break, the else block is skipped, and "Done!" is not printed.

    Reverse for Loop 

    Sometimes, you need to iterate a sequence in reverse order. The for loop in Python allows you to perform backward iteration. Instead of iterating from the first element to the last element, a reverse for loop starts from the last element and iterates backward until the first element.
     
     There are two ways to iterate a for loop in reverse order:

    Backward Iteration Using the reversed() Function

    You can use the built-in reversed() function in Python to perform a reverse iteration over a sequence. The reversed() function returns an iterator that iterates over a sequence's members in the opposite order. After that, you can iterate over the reversed sequence and process the elements one by one using a for loop.

    Here’s an example that demonstrates the usage of reversed() function:

    nums = [1, 3, 5, 16, -7, 9, 7]
    for num in reversed(nums):
    print(num)

    Output:

    7 
    9 
    -7 
    16 
    5 
    3 
    1 
    

    In the above example, the reversed() function yields the elements of nums in reverse order. The for loop iterates over each element in the reversed sequence. It starts from the last element of nums ("7") and continues backward until the first element ("1").

    Reverse for Loop Using range()

    You can also use the range() function to perform reverse iteration over a sequence. As mentioned, the range function takes in start, stop and step values. To iterate the sequence in reverse order, you can set the step to -1.

    Here’s an example that demonstrates the usage of range function for reverse loop:

    for i in range(5, 0, -1):
    print(i)

    Output:

    5
    4
    3
    2
    1

    In this example, the range() function is used to create a sequence of numbers starting from 5 and ending at 1 (inclusive) with a step of -1. This step value ensures that the iteration occurs in reverse order.

    Nested for Loops 

    In Python, you can nest for loops by putting one inside another. This enables you to execute multiple iterations inside of another loop. Before moving on to the next iteration of the outer loop, each repetition of the outer loop causes the inner loop to finish all of its iterations. When you need to iterate over many dimensions or execute operations on combinations of elements, nested for loop in Python come in handy.

    Here's an example that demonstrates nested for loops:

    rows = 3
    cols = 4
    for i in range(rows):
    for j in range(cols):
    print(f"({i}, {j})")

    Output:

    (0, 0)
    (0, 1)
    (0, 2)
    (0, 3)
    (1, 0)
    (1, 1)
    (1, 2)
    (1, 3)
    (2, 0)
    (2, 1)
    (2, 2)
    (2, 3)

    In this example, you have two nested for loops. The outer loop iterates over the values from 0 to 2 (rows). The inner loop iterates over the values from 0 to 3 (cols). The inner loop completes all of its iterations during each cycle of the outer loop. The current values of i and j, which stand for the row and column indices, respectively, are shown by the print() instruction inside the inner loop.

    Note: If the break statement is used inside a nested loop in Python (loop inside another loop), it will terminate the innermost loop.

    While Loop Inside for Loop

    In Python, you may combine both loop types by putting a while loop inside a for loop. This enables conditional iterations to be performed within each iteration of the outer for loop. While the provided condition is true, the while loop continually runs its block of code, and this process is repeated for each iteration of the outer for loop.

    Here's a nested while loop in Python example inside a for loop:

    numbers = [1, 2, 3, 4, 5]
    for num in numbers:
        i = 0
        while i < num:
            print(i)
            i += 1
        print("-----")

    Output:

    -----
    0
    -----
    0
    1
    -----
    0
    1
    2
    -----
    0
    1
    2
    3
    -----
    0
    1
    2
    3
    4

    Inside the for loop, there is a while loop that initializes a variable i to 0. While i is smaller than the current value of num, the while loop continues to run. During each iteration of the while loop, the value of i is printed, incremented by 1, and the process continues until i becomes equal to num.

    After the while loop completes for each num, a separator line ("-----") is printed to separate the iterations.

    For Loop in One Line 

    With Python, you have the freedom to create a for loop in a single line of code using "list comprehension." List comprehensions provide a concise way to create new lists by iterating over an existing sequence or iterable. They let you combine the steps of making a list and going over each item in a list into a single line.

    Here's an example that demonstrates a for loop in one line using list comprehension:

    numbers = [1, 2, 3, 4, 5]
    squared_numbers = [num ** 2 for num in numbers]
    print(squared_numbers)

    Output:

    [1, 4, 9, 16, 25]

    In this example, the list comprehension performs a for loop in one line. It iterates over each element (num) in the numbers list and applies the expression num ** 2 to square each number. The resulting squared numbers are collected into a new list called squared_numbers.

    Accessing the Index in for Loop 

    The enumerate() method in Python allows you to retrieve each element's index while you iterate through a list of elements. The iterator that the enumerate() method returns yields pairs of the index and the relevant element from an iterable or sequence. This offers a convenient method for quickly accessing the value and index of each element inside a for loop.

    Here's an example that demonstrates accessing for loop in Python with index:

    fruits = ['apple', 'banana', 'orange']
    for index, fruit in enumerate(fruits):
    print(f"Index: {index}, Fruit: {fruit}")

    Output:

    Index: 0, Fruit: apple
    Index: 1, Fruit: banana
    Index: 2, Fruit: orange

    In this example, the enumerate() function is used in combination with the fruits list. The for loop repeatedly goes over the pairs of index and fruit, where the index denotes the current element's index and fruit its value. The output shows the index and corresponding fruit for each element in the fruits list.

    Iterate String Using for Loop 

    You can also use a for loop in Python to iterate over a string. Strings are basically collections of characters, thus using a for loop lets you access each character in the string separately.

    Here's an example that demonstrates iterating over a string using a for loop:

    name = "KnowledgeHut"
    for char in name:
        print(char)

    Output:

    K
    n
    o
    w
    l
    e
    d
    g
    e
    H

    Similarly, you can iterate through the string in reverse order or only over a particular set of characters by using the range function.

    Iterate List Using for Loop 

    You can easily iterate over a list using a for loop in Python. The for loop allows you to access each element of the list individually and perform operations on them.

    Here's an example that shows how to iterate over a list using a for loop in Python:\

    numbers = [1, 2, 3, 4, 5]
    for num in numbers:
    print(num)

    Output:

    1
    2
    3
    4
    5

    You can also use the range function to iterate over the list as shown below:

    numbers = [1, 2, 3, 4, 5]
    
    for i in range(len(numbers)):
    print(i)

    Output:

    1
    2
    3
    4
    5

    Wrapping Up 

    In this tutorial, you have explored the concept of for loops in Python. The tutorial focused on important concepts related to for loops, such as loop control statements like break, continue, and pass. Moreover, the tutorial also discussed about concepts such as else block in loops, reverse iteration, and the range function.

    With this knowledge, you are ready to utilize the for loop effectively in your Python programs, making your code more efficient, concise, and expressive. 

    If you're looking to explore more about Python and its built-in functions, you can check out KnowledgeHut’s Python Programming Classes that are designed to help you excel in Python.

    Frequently Asked Questions (FAQs)

    1Can a for loop iterate over a range of numbers?

    Yes, a for loop can iterate over a range of numbers in Python using the built-in range() function.

    2How do you write a range in a for loop in Python?

    To write a range in a for loop in Python, you can use the range() function. The range function takes in the start, stop, and step parameters to define the range of numbers to iterate over.

    3How does a for loop work with range?

    When a for loop works with a range, it iterates over the numbers specified in the range. The loop variable takes on the value of each number in the range during each iteration.

    4What are the 3 parameters of the range function in a for loop?

    The three parameters of the range function in a for loop are: start (optional, default is 0), stop (required), and step (optional, default is 1). The start parameter defines the starting number of the range, the stop parameter defines the ending number (exclusive), and the step parameter defines the increment between numbers in the range.

    Profile

    Ashutosh Krishna

    Author

    Ashutosh is an Application Developer at Thoughtworks. Apart from his love for Backend Development and DevOps, he has a keen interest in writing technical blogs and articles. 

    Share This Article
    Ready to Master the Skills that Drive Your Career?

    Avail your free 1:1 mentorship session.

    Select
    Your Message (Optional)

    Upcoming Programming Batches & Dates

    NameDateFeeKnow more
    Course advisor icon
    Course Advisor
    Whatsapp/Chat icon