For Loops

Welcome to the essential building block of Python programming: for loops. Whether you're automating repetitive tasks, processing data collections, or simply navigating through items one by one, for loops provide a clean, readable, and powerful way to execute your code repeatedly.

In this lesson, we'll explore the anatomy of for loops, see them in action with various data types, and understand their practical applications. By the end, you’ll be comfortable creating for loops that make your Python programs more efficient and expressive.

Understanding the Purpose of For Loops

Imagine you have a list of names, and you want to greet each person individually. Without loops, you would have to write repetitive code for each name:

📌 Deep Dive: Greeting Without a Loop

PYTHON
print("Hello, Alice!")
print("Hello, Bob!")
print("Hello, Charlie!")
print("Hello, Diana!")
Output
Hello, Alice! Hello, Bob! Hello, Charlie! Hello, Diana!

This approach quickly becomes unmanageable as the number of items grows or changes dynamically. Instead, using a for loop allows you to repeat an action for each item in a collection efficiently:

Basic Syntax of a For Loop

The general structure of a for loop in Python is:

for variable in iterable:
    # do something with variable

Here:

  • variable is a temporary name you assign for the current item in the loop.
  • iterable is any sequence or collection (like a list, string, or range) you want to iterate over.

Each time the loop runs, variable takes on the next value from iterable, and the indented block inside the loop executes.

Looping Over a List

Let's put this into practice by looping over a list of fruits and printing each one:

📌 Deep Dive: Looping Over a List

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

for fruit in fruits:
    print(fruit)
Output
apple banana cherry date

Notice how the loop automatically takes each element from the list and assigns it to the variable fruit, which you can then use inside the loop body.

Looping Over Other Iterables: Strings and Ranges

For loops are not limited to lists. You can iterate over any iterable object, such as strings and ranges:

  • Strings: Iterate over each character.
  • Ranges: Generate a sequence of numbers.

📌 Deep Dive: Looping Over a String

PYTHON
for letter in "Python":
    print(letter)
Output
P y t h o n

📌 Deep Dive: Looping Using range()

PYTHON
for num in range(5):
    print(num)
Output
0 1 2 3 4

range(5) generates numbers from 0 up to (but not including) 5.

Why Use For Loops? Efficiency and Readability

For loops help avoid repetitive code and make your programs scalable. Instead of writing tens or hundreds of lines for repetitive tasks, you write concise loops that automatically handle iteration.

💡 Tip:

Using for loops also reduces human error — imagine manually typing repetitive lines; a small typo can cause bugs. Loops ensure consistent execution for each iteration.

Controlling Loop Execution

Within a for loop, you can use control statements like break and continue to alter the flow:

  • break stops the loop entirely.
  • continue skips the current iteration and moves to the next one.

📌 Deep Dive: Using break and continue

PYTHON
numbers = [1, 2, 3, 4, 5, 6]

for num in numbers:
    if num == 4:
        print("Found 4, stopping loop.")
        break
    if num % 2 == 0:
        print(f"{num} is even, skipping.")
        continue
    print(f"Number: {num}")
Output
Number: 1 2 is even, skipping. Number: 3 Found 4, stopping loop.

In this example:

  • Even numbers are skipped with continue.
  • When the loop reaches 4, it prints a message and exits with break.

Looping with Indexes

Sometimes you need the index of the current item in addition to its value. Python’s built-in enumerate() function makes this easy:

📌 Deep Dive: Using enumerate()

PYTHON
colors = ["red", "green", "blue"]

for index, color in enumerate(colors):
    print(f"Color {index}: {color}")
Output
Color 0: red Color 1: green Color 2: blue

Here, enumerate() returns pairs of (index, value), which you unpack directly in the loop.

Comparing For Loops with While Loops

Both for and while loops repeat code, but they serve different purposes:

For Loops vs While Loops
For LoopWhile Loop
Iterates over a sequence or iterable directly. Repeats while a condition remains true.
Great for finite, known collections. Ideal for unknown or condition-based repetitions.
Less prone to infinite loops. Requires careful condition management to avoid infinite loops.

In practice, use for loops when you have a collection or a known sequence. Use while loops when you want to continue until some condition changes.

Nesting For Loops

You can place a for loop inside another for loop to iterate over nested structures like lists of lists.

📌 Deep Dive: Nested For Loops

PYTHON
matrix = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
]

for row in matrix:
    for num in row:
        print(num, end=" ")
    print()
Output
1 2 3 4 5 6 7 8 9

Here, the outer loop iterates through each row (which itself is a list), while the inner loop iterates through each element in that row.

Common Pitfalls and How to Avoid Them

⚠️ Beware of Modifying the Iterable While Looping

Changing the size of a list (e.g., adding or removing items) while iterating can cause unexpected behavior or runtime errors. Instead, create a copy of the list or collect changes to apply after the loop.

⚠️ Indentation Matters

Python’s for loops use indentation to define the loop body. Make sure all statements inside the loop are properly indented; otherwise, your code may not execute as expected or raise errors.

Practical Examples and Use Cases

Example 1: Summing Numbers

Calculate the sum of numbers from 1 to 10:

📌 Deep Dive: Summing with a For Loop

PYTHON
total = 0
for i in range(1, 11):
    total += i
print("Sum:", total)
Output
Sum: 55

Example 2: Building a List with For Loops

Create a list of squares of numbers from 1 to 5:

📌 Deep Dive: Creating a List Using a For Loop

PYTHON
squares = []
for num in range(1, 6):
    squares.append(num ** 2)
print(squares)
Output
[1, 4, 9, 16, 25]

Example 3: Iterating Through Dictionaries

You can loop through dictionaries to access keys, values, or both:

📌 Deep Dive: Looping Over a Dictionary

PYTHON
person = {"name": "Alice", "age": 30, "city": "Paris"}

for key, value in person.items():
    print(f"{key}: {value}")
Output
name: Alice age: 30 city: Paris

Summary: Mastering For Loops

Let's recap what you’ve learned about for loops:

  • They iterate over items in sequences or iterables like lists, strings, ranges, and more.
  • The syntax is simple: for variable in iterable: followed by an indented block.
  • Control statements break and continue allow you to alter loop execution.
  • enumerate() helps access item indexes alongside their values.
  • Nested for loops enable iterating complex nested data structures.
  • Be mindful of modifying iterables during iteration and maintain proper indentation.
Architecture of For Loops
Architecture of For Loops

For loops are fundamental to writing efficient Python code. Practice writing loops with different data types and control flow to deepen your understanding.