0%

19- The for Loop

Iterate over any sequence. Loop through lists, strings, dictionaries, and ranges. The most common loop in Python.

You have a list of names. You want to greet each one. You have a string. You want to print each character. You have a dictionary. You want to process every key-value pair. What do you do? You use a for loop. The for loop in Python is different from other languages. In C or Java, a for loop counts numbers. In Python, a for loop iterates over items directly. You do not need an index variable. You do not need to know the length. You just say “for each item in this collection, do something.” This is called iteration. It is one of the most powerful and frequently used patterns in programming.

🕯️ Magic Note

Python’s for loop works with any iterable object. Lists, strings, tuples, dictionaries, sets, files, and even custom objects that implement iteration. This is the Iterator Protocol, and it is a core design principle of Python. If you can loop over it with for, it is iterable.

Basic for Loop with Lists
The simplest and most common use of for is iterating over a list.

Python

fruits = [“apple”, “banana”, “cherry”, “date”]

for fruit in fruits:

print(f”I like {fruit}”)

# Output:

# I like apple

# I like banana

# I like cherry

# I like date

💡 Read for fruit in fruits as “for each fruit in the list of fruits”. This natural language style is one of the reasons Python is so readable.
Looping Through Strings
Strings are sequences of characters. You can loop through each character.

Python

word = “Python”

for letter in word:

print(f”Letter: {letter}”)

# Output:

# Letter: P

# Letter: y

# Letter: t

# Letter: h

# Letter: o

# Letter: n

Looping Through Tuples
Tuples work exactly like lists in a for loop.

Python

colors = (“red”, “green”, “blue”)

for color in colors:

print(f”Color: {color}”)

# Output:

# Color: red

# Color: green

# Color: blue

Looping Through Dictionaries
Dictionaries have multiple ways to loop. Choose based on what you need.

Python

person = {“name”: “Emma”, “age”: 25, “city”: “London”}

# Loop through keys (default)

for key in person:

print(key)

# name

# age

# city

# Loop through values

for value in person.values():

print(value)

# Emma

# 25

# London

# Loop through both key and value (most common)

for key, value in person.items():

print(f”{key}: {value}”)

# name: Emma

# age: 25

# city: London

🕯️ Magic Note

The pattern for key, value in dictionary.items(): is one of the most useful idioms in Python. It unpacks each key-value pair into two variables in one line. Elegant and readable.

The range() Function
Sometimes you need to loop a specific number of times. Sometimes you need the index of each item. The range() function generates sequences of numbers for exactly this purpose.

Python

# range(stop) – from 0 to stop-1

for i in range(5):

print(i, end=” “)

# 0 1 2 3 4

# range(start, stop) – from start to stop-1

for i in range(2, 6):

print(i, end=” “)

# 2 3 4 5

# range(start, stop, step) – with step size

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

print(i, end=” “)

# 0 2 4 6 8

# Negative step (count downwards)

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

print(i, end=” “)

# 5 4 3 2 1

💡 range() does not create a list of all numbers. It generates numbers one at a time as needed. This is memory efficient, even for range(1000000).
Looping with Index: enumerate()
When you need both the item and its position, use enumerate(). It returns pairs of (index, value).

Python

colors = [“red”, “green”, “blue”, “yellow”]

# Using enumerate

for index, color in enumerate(colors):

print(f”{index}: {color}”)

# Output:

# 0: red

# 1: green

# 2: blue

# 3: yellow

# enumerate with custom start value

for index, color in enumerate(colors, start=1):

print(f”{index}: {color}”)

# 1: red

# 2: green

# 3: blue

# 4: yellow

🕯️ Magic Note

enumerate() is more Pythonic than using range(len(list)). It is cleaner, faster, and directly expresses your intent: “I need both the index and the value.”

Looping Through Multiple Lists: zip()
When you have two or more lists of the same length and want to loop through them together, use zip().

Python

names = [“John”, “Sara”, “Mike”]

scores = [95, 87, 92]

for name, score in zip(names, scores):

print(f”{name}: {score}”)

# Output:

# John: 95

# Sara: 87

# Mike: 92

# zip with more than two iterables

ages = [25, 30, 28]

for name, score, age in zip(names, scores, ages):

print(f”{name} | Score: {score} | Age: {age}”)

⚠️ zip() stops at the shortest iterable. If your lists have different lengths, the extra items are ignored. Use itertools.zip_longest() if you need to keep all items.
List Comprehensions (Loop in One Line)
For simple loops that create a new list, you can use a list comprehension. It is shorter and often faster.

Python

# Regular for loop

squares = []

for x in range(1, 6):

squares.append(x ** 2)

print(squares) # [1, 4, 9, 16, 25]

# List comprehension (same result)

squares = [x ** 2 for x in range(1, 6)]

print(squares) # [1, 4, 9, 16, 25]

# With condition (filter)

evens = [x for x in range(10) if x % 2 == 0]

print(evens) # [0, 2, 4, 6, 8]

💡 Use list comprehensions for simple transformations. Use regular for loops for complex logic, side effects (like printing), or when readability suffers.
Nested for Loops
You can put a for loop inside another for loop. This is useful for working with nested data structures like matrices.

Python

matrix = [

[1, 2, 3],

[4, 5, 6],

[7, 8, 9]

]

for row in matrix:

for item in row:

print(item, end=” “)

print() # New line after each row

# Output:

# 1 2 3

# 4 5 6

# 7 8 9

🕯️ Magic Note

Nested loops multiply the number of iterations. If the outer loop runs 10 times and the inner loop runs 10 times, the inner body runs 100 times. Be mindful of performance with large datasets.

The else Clause in for Loops
A less known feature: for loops can have an else clause. The else block runs only if the loop completes normally (without a break). Useful for search loops.

Python

numbers = [1, 3, 5, 7, 9]

search_for = 4

for num in numbers:

if num == search_for:

print(f”Found {search_for}”)

break

else:

print(f”{search_for} not found”)

# Output: 4 not found

⚠️ The else in a for loop runs when there is no break. This is counterintuitive to many programmers (it is not “else” as in “if-else”). Use it sparingly and document clearly.
Looping Through Files
Files are iterable. You can loop through a file line by line without reading the entire file into memory.

Python

# Reading a file line by line (memory efficient)

with open(“data.txt”, “r”) as file:

for line in file:

print(line.strip()) # strip removes newline

Common Mistakes with for Loops
  • Forgetting the colon : at the end of the for line
  • Modifying a list while iterating over it (causes skipped items or errors)
  • Using range(len(list)) when enumerate() would be better
  • Forgetting that range() stops before the stop value
  • Using for with a dictionary but expecting key-value pairs (use .items())
  • Creating huge lists with list(range(1000000)) when you just need to iterate
Check Your Understanding
  • Write a for loop that prints each fruit in the list [“apple”, “banana”, “cherry”].
  • How do you loop through a dictionary and print both keys and values?
  • What does range(2, 10, 3) produce?
  • Write a list comprehension that creates a list of squares for numbers 1 through 10.
  • What is the difference between for item in list and for i in range(len(list))?
  • How do you loop through two lists at the same time?

⚡ Whisper

The for loop is a gentle guide. It walks through your collection, one item at a time, and hands each piece to you. You do not need to count. You do not need to know the length. You just say “for each” and Python understands. This is not just a loop. It is a philosophy. Work with the data directly. Do not fight it. Do not manage indices unless you must. Let Python do the counting. You focus on what matters: what to do with each item. The for loop is patient. It will visit every item, no matter how many. It will stop when the collection ends. Trust it. Use it. It is one of the first spells you learned, and it will be one of the last you forget.

Related posts