Back to Home 22 lessons Pyodide ready

Python Loops
From for to mastery

Everything you need to master iteration in Python: for loops, while loops, nested loops, loop control, comprehensions, and real-world patterns. 22 interactive lessons — crafted by @PoeticGlenn.

What you will learn

Master every iteration pattern in Python: for and while loops, range(), break, continue, else clauses, nested loops, list comprehensions, enumerate(), zip(), and production-grade iteration patterns. All with step‑by‑step code explanations from @PoeticGlenn.

Why Mastering Loops Changes Everything

Loops are the heartbeat of programming. Without iteration, you'd write the same code over and over — a nightmare for any developer. Mastering loops means you can process thousands of data points, automate repetitive tasks, and build complex systems with just a few lines of code. @PoeticGlenn designed this guide to take you from the simplest for loop to advanced iteration patterns used in production Python codebases.

Automation Power

Automate anything — from file processing to data transformation — with clean, readable loops.

Data Processing

Iterate over millions of records efficiently. Learn the patterns that data engineers use daily.

Algorithm Foundation

Every search, sort, and recursive algorithm depends on solid loop fundamentals. Build your foundation here.

This isn't just a tutorial — it's a complete mental model for iteration in Python. Every concept is reinforced with runnable code, step‑by‑step breakdowns, and real‑world patterns you'll use every day. 🐍

Advertisement

Every Programmer Must Master Loops — Here's Why

If you write code that processes data, automates tasks, or builds applications, you must understand loops deeply. This curriculum, curated by @PoeticGlenn, is foundational. Here's why every developer needs these skills.

⚡ Efficiency at Scale

Loops let you process hundreds, thousands, or millions of items with the same few lines of code. Without loops, your code would explode in size. With them, you scale effortlessly.

🧠 Universal Skill

Every programming language has loops. Master them in Python, and you've mastered them everywhere. The patterns you learn here — iteration, control flow, comprehensions — transfer to any language.

📊 Data Is Everywhere

From CSV files to API responses to database rows, data comes in collections. Loops are how you traverse, transform, and analyse that data. This curriculum gives you the tools.

⚙️ Algorithm Foundation

Every algorithm — searching, sorting, graph traversal, dynamic programming — relies on iteration. Strong loop skills are the prerequisite for advanced computer science.

@PoeticGlenn says: "Loops are where the magic happens. They turn repetitive work into elegant, expressive code. Master them, and you master automation."

Why Iteration Is a Cornerstone of Software Development

In the broader programming ecosystem, loops are not a "nice‑to‑have" — they're a fundamental building block that underpins everything from simple scripts to operating systems. This curriculum, designed by @PoeticGlenn, reflects the iteration patterns used in millions of production systems worldwide.

Data Engineering

ETL pipelines, data validation, and transformation all rely on iteration. Loops are how you process every row, every file, every record.

Backend Systems

Web frameworks, API handlers, and background workers use loops to handle requests, process queues, and manage state. Iteration is everywhere.

AI & Machine Learning

Training loops, epoch iterations, batch processing — ML is fundamentally about iterating over data until the model converges. Loops are the engine of AI.

The curriculum you're about to explore is not academic — it's the practical foundation used by thousands of open‑source projects and Fortune 500 companies. Every concept maps directly to real‑world problems you'll face as a professional developer.

➡️ The for Loop — Your Iteration Workhorse

The for loop in Python iterates over any iterable: lists, tuples, strings, dicts, and more.

📝 1.1 Basic for Loop — Iterate Over a List

The simplest form: loop over a list and do something with each element.

Step-by-step explanation:

  • Step 1: Define a list fruits = ["apple", "banana", "cherry"].
  • Step 2: Use for fruit in fruits: to iterate over each element.
  • Step 3: Inside the loop, fruit takes the value of each element in turn.
  • Step 4: Print each fruit with an f-string to display it.
  • Step 5: After the loop, print a summary message.
python
def basic_for_loop():
    fruits = ["apple", "banana", "cherry"]

    for fruit in fruits:
        print(f"I like {fruit}")

    print("Done!")

basic_for_loop()
💡 The loop variable (fruit) is created when the loop starts and is available after the loop ends. It holds the last value from the iteration.

📝 1.2 Iterating Over a String

Strings are iterable — each character is one item.

Step-by-step explanation:

  • Step 1: Define a string word = "Python".
  • Step 2: Use for char in word: to iterate over each character.
  • Step 3: Inside the loop, each char is a one-character string.
  • Step 4: Print each character with a separator to show them individually.
  • Step 5: Also show the character's uppercase version.
python
def string_iteration():
    word = "Python"

    for char in word:
        print(f"Char: {char} → uppercase: {char.upper()}")

string_iteration()

🔢 The range() Function — Numeric Iteration

range() generates sequences of numbers. It's the go‑to tool for counting loops.

🔢 2.1 range(stop) — Count from 0 to stop-1

A single argument creates a range from 0 up to (but not including) the stop value.

Step-by-step explanation:

  • Step 1: Call range(5) to generate numbers 0, 1, 2, 3, 4.
  • Step 2: Use for i in range(5): to iterate over these numbers.
  • Step 3: Inside the loop, i takes each value from 0 to 4.
  • Step 4: Print the square of each number using i ** 2.
  • Step 5: Use list(range(5)) to visualise the sequence.
python
def range_stop_demo():
    print("Squares of 0-4:")
    for i in range(5):
        print(f"{i}² = {i ** 2}")

    print(f"\nRange as list: {list(range(5))}")

range_stop_demo()

🔢 2.2 range(start, stop, step) — Full Control

Specify the start, stop, and step size for custom sequences.

Step-by-step explanation:

  • Step 1: Use range(2, 10, 2) to generate even numbers from 2 to 8.
  • Step 2: Iterate over the range and print each value.
  • Step 3: Use range(10, 0, -1) to count backwards from 10 to 1.
  • Step 4: Demonstrate how list() converts a range to a list for visualisation.
  • Step 5: Show a practical use: summing a range with sum(range(1, 101)).
python
def range_full_demo():
    print("Even numbers 2-8:")
    for i in range(2, 10, 2):
        print(i, end=" ")
    print()

    print("\nCountdown 10-1:")
    for i in range(10, 0, -1):
        print(i, end=" ")
    print()

    print(f"\nSum 1-100: {sum(range(1, 101))}")

range_full_demo()
✨ range() is memory‑efficient — it doesn't store all values, just the start, stop, and step. Use list(range(...)) only when you need the actual list.

📋 Iterating Over Sequences — Lists, Tuples, Dicts

Python's for loop works with any iterable. Learn the patterns for each data structure.

📋 3.1 Iterating Over a List with Index

Sometimes you need both the index and the value. Use enumerate() or range(len()).

Step-by-step explanation:

  • Step 1: Define a list of colors.
  • Step 2: Use enumerate(colors) to get both index and value.
  • Step 3: In the loop, idx is the index and color is the value.
  • Step 4: Print both with a formatted message.
  • Step 5: Alternative: use range(len(colors)) to loop by index.
python
def list_with_index():
    colors = ["red", "green", "blue", "yellow"]

    print("Using enumerate():")
    for idx, color in enumerate(colors):
        print(f"{idx}: {color}")

    print("\nUsing range(len()):")
    for i in range(len(colors)):
        print(f"{i}: {colors[i]}")

list_with_index()
💡 enumerate() is cleaner and more Pythonic than range(len()). Use it whenever you need the index.

📋 3.2 Iterating Over a Dictionary

Dictionaries can be iterated by keys, values, or key‑value pairs.

Step-by-step explanation:

  • Step 1: Define a dictionary person = {"name": "Alice", "age": 30, "city": "Paris"}.
  • Step 2: Iterate over keys with for key in person:.
  • Step 3: Iterate over values with for value in person.values():.
  • Step 4: Iterate over key‑value pairs with for key, value in person.items():.
  • Step 5: Print each iteration style with descriptive messages.
python
def dict_iteration():
    person = {"name": "Alice", "age": 30, "city": "Paris"}

    print("Keys:")
    for key in person:
        print(f"  {key}")

    print("\nValues:")
    for value in person.values():
        print(f"  {value}")

    print("\nKey-Value pairs:")
    for key, value in person.items():
        print(f"  {key}: {value}")

dict_iteration()

🔄 The while Loop — Repeat Until Condition

while loops run as long as a condition is True. Use them when you don't know how many iterations you need.

🔄 4.1 Basic while Loop — Counting

A simple counter that increments until a condition is met.

Step-by-step explanation:

  • Step 1: Initialize count = 0 as the loop variable.
  • Step 2: Use while count < 5: as the loop condition.
  • Step 3: Inside the loop, print the current count.
  • Step 4: Increment count by 1 — this is critical to avoid an infinite loop.
  • Step 5: After the loop, print a completion message.
python
def while_count():
    count = 0
    while count < 5:
        print(f"Count: {count}")
        count += 1
    print("Loop finished!")

while_count()
⚠️ Always ensure the condition changes inside the loop. Forgetting to increment count would create an infinite loop!

🔄 4.2 while with User Input

A classic pattern: keep asking until the user provides valid input.

Step-by-step explanation:

  • Step 1: Initialize valid = False as a flag.
  • Step 2: Use while not valid: to loop until valid input is received.
  • Step 3: Inside the loop, ask the user for a number.
  • Step 4: Try to convert the input to int.
  • Step 5: If conversion succeeds, set valid = True and break the loop.
  • Step 6: If conversion fails, show an error and continue.
  • Step 7: After the loop, display the valid number.
python
def while_user_input():
    valid = False
    while not valid:
        try:
            num = int(input("Enter a number: "))
            valid = True
        except ValueError:
            print("That's not a valid number. Try again.")
    print(f"Valid number: {num}")

while_user_input()

⏹️ Loop Control — break, continue, pass

Control the flow of your loops with these three powerful statements.

⏹️ 5.1 break — Exit the Loop Early

break immediately terminates the loop, regardless of the condition.

Step-by-step explanation:

  • Step 1: Loop over numbers 1 to 10 using for i in range(1, 11).
  • Step 2: Inside the loop, check if i == 6.
  • Step 3: If true, print "Breaking!" and use break to exit.
  • Step 4: Otherwise, print the current number.
  • Step 5: After the loop, print a message indicating the loop ended.
python
def break_demo():
    for i in range(1, 11):
        if i == 6:
            print("Breaking!")
            break
        print(i)
    print("Loop exited.")

break_demo()

⏹️ 5.2 continue — Skip to Next Iteration

continue skips the rest of the current iteration and moves to the next.

Step-by-step explanation:

  • Step 1: Loop over numbers 1 to 10.
  • Step 2: Check if i % 2 == 0 (even number).
  • Step 3: If even, print "Skipping even" and use continue.
  • Step 4: If odd, print the number.
  • Step 5: The loop continues normally after continue is executed.
python
def continue_demo():
    for i in range(1, 11):
        if i % 2 == 0:
            print(f"Skipping {i} (even)")
            continue
        print(f"Odd number: {i}")

continue_demo()

⏹️ 5.3 pass — Placeholder

pass does nothing. It's a placeholder when syntax requires a statement but you don't want to do anything.

Step-by-step explanation:

  • Step 1: Use for i in range(5): to loop 5 times.
  • Step 2: Inside the loop, use pass as a placeholder.
  • Step 3: In a real program, you'd replace pass with actual logic.
  • Step 4: pass is also useful in if, while, and function definitions.
python
def pass_demo():
    print("Looping with pass:")
    for i in range(5):
        pass
    print("Loop done!")

    print("\nUsing pass in an if statement:")
    x = 10
    if x > 5:
        pass
    else:
        print("x is not greater than 5")

pass_demo()
✨ pass is a no‑op. Use it when you're sketching out code and want to come back later to fill in the logic.

📦 Nested Loops — Loops Inside Loops

Nested loops are loops within loops. They're used for multidimensional data, combinations, and more.

📦 6.1 Multiplication Table

A classic example: generate a multiplication table using nested loops.

Step-by-step explanation:

  • Step 1: Outer loop for i in range(1, 5) for rows.
  • Step 2: Inner loop for j in range(1, 5) for columns.
  • Step 3: Inside the inner loop, calculate i * j.
  • Step 4: Print the result with formatting to align columns.
  • Step 5: After the inner loop, print a newline to start the next row.
python
def multiplication_table():
    for i in range(1, 5):
        for j in range(1, 5):
            print(f"{i * j:4}", end="")
        print()

multiplication_table()

📦 6.2 Iterating Over a Matrix (2D List)

Nested loops are essential for processing two‑dimensional data structures.

Step-by-step explanation:

  • Step 1: Define a 2D list (matrix) with three rows and three columns.
  • Step 2: Outer loop for row in matrix iterates over each row.
  • Step 3: Inner loop for element in row iterates over each element in that row.
  • Step 4: Print each element with a space separator.
  • Step 5: After each row, print a newline for formatting.
python
def matrix_iteration():
    matrix = [
        [1, 2, 3],
        [4, 5, 6],
        [7, 8, 9]
    ]

    for row in matrix:
        for element in row:
            print(element, end=" ")
        print()

matrix_iteration()

⚡ List Comprehensions — Concise Iteration

List comprehensions are a concise way to create lists by applying an expression to each element of an iterable.

⚡ 7.1 Basic List Comprehension

Replace a for loop that builds a list with a single line.

Step-by-step explanation:

  • Step 1: Start with a list of numbers: [1, 2, 3, 4, 5].
  • Step 2: Use a comprehension: [x**2 for x in numbers].
  • Step 3: The expression x**2 is applied to each element x.
  • Step 4: The result is a new list with the squares.
  • Step 5: Compare with a traditional for loop to see the difference.
python
def list_comp_demo():
    numbers = [1, 2, 3, 4, 5]
    squares = [x**2 for x in numbers]
    print(f"Numbers: {numbers}")
    print(f"Squares: {squares}")

    print(f"Squares (loop): {squares_loop}")

list_comp_demo()

⚡ 7.2 Comprehension with Condition

Add an if clause to filter elements.

Step-by-step explanation:

  • Step 1: Define a list of numbers.
  • Step 2: Use comprehension with a condition: [x for x in numbers if x % 2 == 0].
  • Step 3: Only even numbers are included in the result.
  • Step 4: This is equivalent to a for loop with an if statement.
  • Step 5: Show both the comprehension and the loop equivalent.
python
def comp_with_condition():
    numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
    evens = [x for x in numbers if x % 2 == 0]
    print(f"All: {numbers}")
    print(f"Evens: {evens}")

    print(f"Evens (loop): {evens_loop}")

comp_with_condition()
💡 List comprehensions are more Pythonic and often faster than traditional loops for building lists. Use them to write clean, expressive code.

➕ The else Clause in Loops

The else clause in a loop runs only if the loop completes normally (without a break).

➕ 8.1 for with else

Use else to detect whether a loop was interrupted by break.

Step-by-step explanation:

  • Step 1: Search for a number in a list.
  • Step 2: If found, print a message and break.
  • Step 3: If the loop completes without finding the number, the else block runs.
  • Step 4: The else block only runs if no break occurred.
python
def for_else_demo():
    numbers = [1, 3, 5, 7, 9]
    search = 5

    for num in numbers:
        if num == search:
            print(f"Found {search}!")
            break
    else:
        print(f"{search} not found.")

for_else_demo()
✨ The else clause is often called the "no‑break" clause. It's a clean way to handle "not found" cases without using a flag variable.

➕ 8.2 while with else

The same pattern works with while loops.

Step-by-step explanation:

  • Step 1: Initialize attempts = 0.
  • Step 2: Use while attempts < 3: to limit attempts.
  • Step 3: If the user enters the correct password, print success and break.
  • Step 4: If the loop ends without a break, the else block runs.
python
def while_else_demo():
    password = "secret"
    attempts = 0

    while attempts < 3:
        guess = input("Enter password: ")
        attempts += 1
        if guess == password:
            print("Access granted!")
            break
    else:
        print("Access denied. Too many attempts.")

while_else_demo()

🔗 enumerate() and zip() — Powerful Iteration Tools

These built‑ins make iteration more expressive and powerful.

🔗 9.1 enumerate() — Index and Value

enumerate() adds a counter to an iterable, yielding index and value pairs.

Step-by-step explanation:

  • Step 1: Define a list of items.
  • Step 2: Use enumerate(items) in a for loop.
  • Step 3: Each iteration yields (idx, item).
  • Step 4: Print the index and value with a formatted message.
  • Step 5: You can also specify a start value: enumerate(items, start=1).
python
def enumerate_demo():
    fruits = ["apple", "banana", "cherry", "date"]

    for idx, fruit in enumerate(fruits):
        print(f"{idx}: {fruit}")

    print("\nStarting at 1:")
    for idx, fruit in enumerate(fruits, start=1):
        print(f"{idx}: {fruit}")

enumerate_demo()

🔗 9.2 zip() — Parallel Iteration

zip() combines multiple iterables into tuples of corresponding elements.

Step-by-step explanation:

  • Step 1: Define two lists: names and ages.
  • Step 2: Use zip(names, ages) to pair them.
  • Step 3: Each iteration yields a tuple (name, age).
  • Step 4: Print each pair with a formatted message.
  • Step 5: zip() stops at the shortest iterable.
python
def zip_demo():
    names = ["Alice", "Bob", "Charlie", "Diana"]
    ages = [30, 25, 35, 28]

    for name, age in zip(names, ages):
        print(f"{name} is {age} years old.")

    print()

    cities = ["New York", "London", "Paris", "Tokyo"]
    for name, age, city in zip(names, ages, cities):
        print(f"{name} ({age}) lives in {city}")

zip_demo()
💡 zip() is perfect for iterating over multiple sequences in parallel. It's memory‑efficient because it yields tuples on the fly.

♾️ Infinite Loops — Power and Responsibility

Infinite loops run forever unless stopped. They're useful for servers, game loops, and event handlers — but dangerous if not controlled.

♾️ 10.1 Intentional Infinite Loop with break

A controlled infinite loop that exits when a condition is met.

Step-by-step explanation:

  • Step 1: Use while True: to create an infinite loop.
  • Step 2: Inside the loop, ask the user for input.
  • Step 3: If the user types "quit", break out of the loop.
  • Step 4: Otherwise, process the input (here we just echo it).
  • Step 5: The loop continues until the break condition is met.
python
def infinite_with_break():
    print("Type 'quit' to exit.")
    while True:
        user_input = input("> ")
        if user_input.lower() == "quit":
            print("Goodbye!")
            break
        print(f"You typed: {user_input}")

infinite_with_break()
⚠️ In a real terminal, an infinite loop without a break would hang the program. Always ensure there's a way out — a break, a keyboard interrupt handler, or a timeout.

♾️ 10.2 Safety with try/except and KeyboardInterrupt

Make your infinite loops responsive to user interrupts (Ctrl+C).

Step-by-step explanation:

  • Step 1: Wrap the infinite loop in a try block.
  • Step 2: Catch KeyboardInterrupt to handle Ctrl+C gracefully.
  • Step 3: In the loop, do useful work (here we simulate with a counter).
  • Step 4: When interrupted, print a message and exit.
  • Step 5: This pattern is used in servers and long‑running processes.
python
def safe_infinite_loop():
    print("Press Ctrl+C to stop.")
    count = 0
    try:
        while True:
            print(f"Running... {count}")
            count += 1
            import time
            time.sleep(0.5)
    except KeyboardInterrupt:
        print("\nStopped by user. Goodbye!")

safe_infinite_loop()
✨ In this browser sandbox, KeyboardInterrupt is simulated — the loop will run a few times and then stop automatically to avoid hanging.

🚀 Real-World Loop Patterns

Putting it all together — iteration patterns used in production Python applications.

🚀 11.1 Processing a File Line by Line

Iterating over a file is one of the most common real‑world uses of loops.

Step-by-step explanation:

  • Step 1: Open a file using with open(...).
  • Step 2: Use for line in file: to iterate over each line.
  • Step 3: Strip the newline character and process the line.
  • Step 4: Count lines, words, or characters as needed.
  • Step 5: The file is automatically closed when the with block exits.
python
def process_file():
    try:
        with open("sample.txt", "r", encoding="utf-8") as f:
            line_count = 0
            word_count = 0
            char_count = 0

            for line in f:
                line_count += 1
                word_count += len(line.split())
                char_count += len(line)

            print(f"Lines: {line_count}")
            print(f"Words: {word_count}")
            print(f"Characters: {char_count}")
    except FileNotFoundError:
        print("File not found.")

process_file()

🚀 11.2 Filtering and Transforming Data

Combine loops with conditions to filter and transform data.

Step-by-step explanation:

  • Step 1: Define a list of raw data (numbers and strings).
  • Step 2: Use a loop to filter out invalid items.
  • Step 3: Transform the valid items (e.g., square numbers).
  • Step 4: Build a new list with the transformed data.
  • Step 5: This pattern is the basis of data pipelines.
python
def filter_transform():
    raw_data = [1, "hello", 3, "world", 5, 6.5, 7, "python"]

    cleaned = []
    for item in raw_data:
        if isinstance(item, (int, float)):
            cleaned.append(item ** 2)

    print(f"Raw: {raw_data}")
    print(f"Cleaned and squared: {cleaned}")

filter_transform()

🚀 11.3 Nested Data — Flattening a List of Lists

Use nested loops to flatten a 2D structure into a 1D list.

Step-by-step explanation:

  • Step 1: Define a list of lists (matrix).
  • Step 2: Use a nested loop: outer loop over rows, inner over elements.
  • Step 3: Append each element to a flat list.
  • Step 4: Print the original matrix and the flattened list.
  • Step 5: This pattern is used in data pre‑processing.
python
def flatten_matrix():
    matrix = [
        [1, 2, 3],
        [4, 5, 6],
        [7, 8, 9]
    ]

    flat = []
    for row in matrix:
        for element in row:
            flat.append(element)

    print(f"Matrix: {matrix}")
    print(f"Flattened: {flat}")

flatten_matrix()

❓ Frequently Asked Questions — Loops

Common questions about Python loops, answered.

When should I use a for loop vs a while loop?

+

Use for when you know how many iterations you need (e.g., iterating over a list, range, or file). Use while when the number of iterations depends on a condition that may change during the loop (e.g., user input, convergence).

How do I loop over a list backwards?

+

Use for item in reversed(my_list): or for i in range(len(my_list)-1, -1, -1):. The reversed() function is more Pythonic.

What is the difference between break and continue?

+

break exits the entire loop immediately. continue skips the rest of the current iteration and moves to the next one. break is terminal; continue is conditional.

What does the else clause in a loop do?

+

The else block runs only if the loop completes normally (without hitting a break). It's often used for "not found" logic.

How do I avoid an infinite loop?

+

Always ensure the loop condition changes inside the loop. For while loops, update the variable that the condition depends on. For controlled infinite loops, always have a break condition.

Are list comprehensions faster than loops?

+

Yes, list comprehensions are often faster because they're implemented in C and optimized for the common case. They're also more readable for simple transformations. However, for complex logic, a for loop may be clearer.

💛 You've Mastered Python Loops

From the foundational for loop to advanced patterns like nested loops and comprehensions, you now have a complete mental model for iteration in Python. You've learned to iterate, control, comprehend, and apply loops in ways that scale from simple scripts to production applications.

This curriculum, crafted by @PoeticGlenn, is designed to be your go‑to reference whenever you need to iterate in Python. Bookmark it, share it with your team, and revisit the lessons as you build more complex systems.

22 lessons 28+ code examples 720+ learners

"Iteration is the essence of programming. Master it, and you can automate, analyse, and build anything." — Glenn Junsay Pansensoy (@PoeticGlenn)