Your Page Title
🔍

    How to use for loop in Python

    A for loop in Python is used to iterate over a sequence (like a list, tuple, string, or range) or other iterable objects. It is a way to repeat a block of code for every item in the sequence.

    Syntax of a for loop

    for item in iterable:
        # Code block to execute for each item
    • item: A variable that iterates over the iterable (such as a list or range) and takes on the value of each element one at a time.
    • iterable: An object containing multiple values (for example, a list, string, or range).
    • The code block in the loop runs once for each item in the iterable.

    Example 1: Iterating through a list

    fruits = ["apple", "banana", "cherry"]
    
    for fruit in fruits:
        print(fruit)

    Output:

    apple
    banana
    cherry
    • Here, the loop variable fruit takes on each value in the list fruits one by one, and the print() function outputs it.

    Example 2: Using range() with a for loop

    The range() function generates a sequence of numbers.

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

    Output:

    0
    1
    2
    3
    4
    • range(5) generates numbers from 0 to 4 (5 is excluded).
    • The loop variable i takes these values one by one.

    Example 3: Iterating through the string

    text = "Jobbinge"
    
    for char in text:
        print(char)
    J
    o
    b
    b
    i
    n
    g
    e
    • The string "Jobbinge" is treated as a sequence of characters.
    • The for loop processes each character one by one.
    • The loop variable char takes each character of the string in order and prints it.

    Example 4: Using else with a for loop

    The else block in a for loop runs after the loop completes normally (without a break).

    numbers = [1, 2, 3]
    
    for num in numbers:
        print(num)
    else:
        print("Loop completed.")

    Output:

    1
    2
    3
    Loop completed.

    Example 5: Breaking out of a loop

    You can use the break statement to exit a loop prematurely.

    for i in range(10):
        if i == 5:
            break
        print(i)

    Output:

    0
    1
    2
    3
    4
    • The loop stops when i is 5.

    Example 6: Skipping iterations with continue

    The continue statement skips the rest of the code in the loop for the current iteration.

    for i in range(5):
        if i == 2:
            continue
        print(i)

    Output:

    0
    1
    3
    4
    • When i is 2, the continue statement skips the print().

    Common Use Cases of for loops

    1. Iterating over lists, dictionaries, and tuples:
    items = {"a": 1, "b": 2, "c": 3}
    for key, value in items.items():
        print(f"{key}: {value}")

    2. Generating a list using a loop and comprehension:

    squares = [x**2 for x in range(5)]
    print(squares)

    3. Performing operations on each element:

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

    Key Points:

    • A for loop is a powerful way to process items in sequences or iterables.
    • You can control the loop with break, continue, and else.
    • Iterables can include not just lists, but strings, tuples, dictionaries, sets, and even custom objects.