On this page

For Loops

What a For Loop Is​

A for loop repeats a block of code for each item in a sequence. Instead of writing the same instruction multiple times, you instruct Python to iterate through values automatically. This mechanism is essential for processing lists, strings, ranges, and other iterable objects.

A for loop always follows the same structure:


for variable in sequence:

    # repeated block

Python assigns each item in the sequence to the loop variable, one at a time, and executes the indented block for each item.

Looping Over a List​

Lists are one of the most common sequences used with for loops.


numbers = [10, 20, 30]



for n in numbers:

    print(n)

The loop runs three times. Each time, n takes the next value from the list.

Looping Over a String​

Strings are sequences of characters. A for loop can process each character individually.


text = "Python"



for ch in text:

    print(ch)

This technique is useful for analyzing or transforming text.

Looping with range()​

The range() function generates a sequence of numbers. It is commonly used when you need a specific number of repetitions.


for i in range(5):

    print(i)

This prints:


0

1

2

3

4

Range Variants​

range() supports start, stop, and step values.


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

    print(i)

This prints even numbers from 2 to 8.

Using the Loop Variable​

The loop variable is available inside the loop block and can be used in expressions.


for i in range(1, 6):

    print("Square of", i, "is", i * i)

Each iteration computes a new result based on the current value of i.

Accumulating Results​

For loops often build or accumulate results.


total = 0



for n in [3, 5, 7]:

    total += n



print("Total:", total)

This pattern appears frequently in data processing tasks.

Nested For Loops​

A loop can appear inside another loop. This is useful for working with multi‑dimensional data or generating combinations.


for x in range(2):

    for y in range(3):

        print(x, y)

Nested loops must be used carefully to maintain clarity.

Why For Loops Matter​

For loops allow you to process sequences, repeat operations, analyze data, and build structured logic. They are essential for tasks such as iterating through lists, reading files line by line, generating patterns, and performing calculations across collections of values. Mastering for loops prepares you for more advanced control‑flow structures and data‑processing techniques in later modules.

Found this helpful? Share the knowledge...

... or support this project to keep it alive!

Buy Me a Coffee

Previous

Match/Case Statements

Next

While Loops