Skip to main content
Editor

Python For Loops: Iterate Over Anything with Examples

Beginner25 min8 exercises125 XP

Leer en españolЧитать на русскомLer em portuguêsอ่านภาษาไทย

0/8 exercises

Imagine you're a teacher with 30 students. You need to print a report card for each one. Would you write 30 separate print statements? Of course not. You'd tell the computer: "for each student, print their report card." That's exactly what a for loop does.

In this tutorial, you'll learn how to use Python's for loop to repeat actions over lists, strings, ranges of numbers, and dictionaries. You'll also discover powerful tools like enumerate() and zip() that make looping even easier.

By the end, you'll be able to process collections of data efficiently instead of writing repetitive code. This is one of the most important skills in programming.

How Does a For Loop Work in Python?

A for loop takes a collection of items and runs the same code once for each item. On every pass through the loop, a variable holds the current item. Python calls each pass an iteration.

Think of it like dealing cards. You pick up the deck, and for each card, you place it face-up on the table. The card changes each time, but the action stays the same.

Your first for loop
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
# Output:
# apple
# banana
# cherry
Output
apple
banana
cherry

Here's the structure: the keyword for, a variable name (fruit), the keyword in, and the collection (fruits), followed by a colon. The indented code below runs once for each item in the list.

On the first iteration, fruit is "apple". On the second, it's "banana". On the third, it's "cherry". After the last item, the loop ends and Python moves on to whatever comes next.

Accumulating a total with a for loop
# The loop variable can be anything you want
numbers = [10, 20, 30, 40]
total = 0
for num in numbers:
total = total + num
print(f"Added {num}, total is now {total}")
print(f"\nFinal total: {total}")
# Output:
# Added 10, total is now 10
# Added 20, total is now 30
# Added 30, total is now 60
# Added 40, total is now 100
#
# Final total: 100
Output
Added 10, total is now 10
Added 20, total is now 30
Added 30, total is now 60
Added 40, total is now 100

Final total: 100

This pattern of starting with a value and updating it in each iteration is called accumulation. You'll use it constantly - for summing numbers, building strings, collecting results, and more.


What Does range() Do in Python?

Sometimes you don't have a list to loop over - you just want to repeat something a specific number of times, or loop through a sequence of numbers. That's what range() is for.

range() generates a sequence of numbers. It doesn't create a list in memory - it produces numbers one at a time as the loop needs them. This makes it efficient even for large ranges.

range() with one argument: stop
# range(5) gives you 0, 1, 2, 3, 4
for i in range(5):
print(i)
# Output:
# 0
# 1
# 2
# 3
# 4
Output
0
1
2
3
4

Notice that range(5) starts at 0 and stops before 5. It gives you exactly 5 numbers: 0 through 4. This "start at zero, stop before the end" pattern is consistent throughout Python.

range() with two arguments: start and stop
# range(start, stop) - starts at start, stops before stop
for i in range(1, 6):
print(i)
# Output:
# 1
# 2
# 3
# 4
# 5
Output
1
2
3
4
5

With two arguments, the first is where to start and the second is where to stop (exclusive). So range(1, 6) gives you 1, 2, 3, 4, 5.

range() with three arguments: start, stop, step
# range(start, stop, step) - count by a custom step
print("Count by 2s:")
for i in range(0, 11, 2):
print(i, end=" ")
print() # newline
print("\nCountdown:")
for i in range(5, 0, -1):
print(i, end=" ")
print("\nBlastoff!")
# Output:
# Count by 2s:
# 0 2 4 6 8 10
#
# Countdown:
# 5 4 3 2 1
# Blastoff!
Output
Count by 2s:
0 2 4 6 8 10 

Countdown:
5 4 3 2 1 
Blastoff!

The third argument is the step - how much to add each time. A step of 2 skips every other number. A negative step counts backwards. You can use any integer step, positive or negative.


How Do You Loop Over Strings and Dictionaries?

For loops work with anything iterable in Python - not just lists and ranges. Strings and dictionaries are two of the most common iterables you'll loop over.

Looping Over a String

When you loop over a string, you get one character at a time. This is useful for counting letters, checking spelling, or processing text character by character.

Looping over a string
word = "Python"
for char in word:
print(char, end=" ")
# Output:
# P y t h o n
Output
P y t h o n

Each iteration gives you the next character. The end=" " in the print function replaces the default newline with a space, so all the characters print on one line.

Counting vowels with a for loop
# Count vowels in a word
word = "programming"
vowel_count = 0
for char in word:
if char in "aeiou":
vowel_count += 1
print(f"\"{word}\" has {vowel_count} vowels")
# Output:
# "programming" has 3 vowels
Output
"programming" has 3 vowels

This example combines a for loop with an if statement. For each character, we check if it's a vowel. If it is, we increment the count. This is the kind of pattern you'll write all the time.

Looping Over a Dictionary

When you loop over a dictionary, you get the keys by default. To get both keys and values, use the .items() method.

Looping over a dictionary
scores = {"Alice": 92, "Bob": 85, "Charlie": 78}
# Looping over keys (default)
print("Students:")
for name in scores:
print(f" {name}")
print()
# Looping over keys and values with .items()
print("Report card:")
for name, score in scores.items():
print(f" {name}: {score}")
# Output:
# Students:
# Alice
# Bob
# Charlie
#
# Report card:
# Alice: 92
# Bob: 85
# Charlie: 78
Output
Students:
  Alice
  Bob
  Charlie

Report card:
  Alice: 92
  Bob: 85
  Charlie: 78

The .items() method returns each entry as a pair of (key, value). By writing for name, score in scores.items(), you unpack each pair into two separate variables. This is cleaner than accessing scores[name] inside the loop.


What Does enumerate() Do in Python?

Sometimes you need both the item AND its position in the list. You could use range(len(list)) and index into the list manually, but Python has a cleaner way: enumerate().

Without enumerate() (ugly)
colors = ["red", "green", "blue"]

for i in range(len(colors)):
    print(f"{i}: {colors[i]}")
With enumerate() (clean)
colors = ["red", "green", "blue"]

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

enumerate() wraps an iterable and gives you pairs of (index, item). You unpack each pair into two variables. Both examples produce the same output, but the enumerate() version is more readable and more Pythonic.

enumerate() with start=1 for numbered lists
tasks = ["Buy groceries", "Clean house", "Walk dog", "Cook dinner"]
print("Today's to-do list:")
for i, task in enumerate(tasks, start=1):
print(f" {i}. {task}")
# Output:
# Today's to-do list:
# 1. Buy groceries
# 2. Clean house
# 3. Walk dog
# 4. Cook dinner
Output
Today's to-do list:
  1. Buy groceries
  2. Clean house
  3. Walk dog
  4. Cook dinner

The start=1 argument tells enumerate() to begin counting from 1 instead of 0. This is perfect for creating numbered lists where "item 0" doesn't make sense to users.


How Does zip() Let You Loop Over Multiple Lists?

What if you have two related lists and you want to process them together? For example, a list of student names and a list of their scores. zip() pairs them up so you can loop through both at once.

Looping over two lists with zip()
names = ["Alice", "Bob", "Charlie"]
scores = [92, 85, 78]
for name, score in zip(names, scores):
result = "Pass" if score >= 80 else "Needs improvement"
print(f"{name}: {score} ({result})")
# Output:
# Alice: 92 (Pass)
# Bob: 85 (Pass)
# Charlie: 78 (Needs improvement)
Output
Alice: 92 (Pass)
Bob: 85 (Pass)
Charlie: 78 (Needs improvement)

zip() takes two or more iterables and combines them element by element. On the first iteration, you get the first item from each list. On the second iteration, you get the second item from each, and so on.

Zipping three lists together
# zip() works with more than two lists
first_names = ["Alice", "Bob", "Charlie"]
last_names = ["Smith", "Jones", "Brown"]
ages = [25, 30, 22]
for first, last, age in zip(first_names, last_names, ages):
print(f"{first} {last}, age {age}")
# Output:
# Alice Smith, age 25
# Bob Jones, age 30
# Charlie Brown, age 22
Output
Alice Smith, age 25
Bob Jones, age 30
Charlie Brown, age 22

What Are Nested For Loops?

You can put a for loop inside another for loop. The inner loop runs completely for each iteration of the outer loop. This is called nesting, and it's how you work with grids, tables, and combinations.

Nested loops: multiplication table
# Multiplication table (1-3)
for row in range(1, 4):
for col in range(1, 4):
result = row * col
print(f"{row} x {col} = {result}")
print() # blank line between rows
# Output:
# 1 x 1 = 1
# 1 x 2 = 2
# 1 x 3 = 3
#
# 2 x 1 = 2
# 2 x 2 = 4
# 2 x 3 = 6
#
# 3 x 1 = 3
# 3 x 2 = 6
# 3 x 3 = 9
Output
1 x 1 = 1
1 x 2 = 2
1 x 3 = 3

2 x 1 = 2
2 x 2 = 4
2 x 3 = 6

3 x 1 = 3
3 x 2 = 6
3 x 3 = 9

When row is 1, the inner loop runs with col going 1, 2, 3. Then row becomes 2, and the inner loop runs again with col going 1, 2, 3. The inner loop starts fresh every time the outer loop moves forward.


Practice Exercises

Time to put your for loop skills to work! These exercises progress from basic iteration to combining loops with the tools you just learned.

Try each exercise on your own before checking the hints. Getting stuck and figuring it out is how you build real skills.

Exercise 1: Print the Shopping List
Write Code

A list of grocery items is given. Use a for loop to print each item on its own line.

Expected output:

milk
eggs
bread
butter
groceries = ["milk", "eggs", "bread", "butter"]
# Use a for loop to print each item
Exercise 2: Sum Numbers 1 to 10
Write Code

Use range() and a for loop to calculate the sum of all numbers from 1 to 10 (inclusive). Print the result.

Expected output:

Sum: 55
# Calculate the sum of numbers 1 through 10 using range()
total = 0
# Write your for loop here
print(f"Sum: {total}")
Exercise 3: Predict the Output
Predict Output

Without running the code, predict exactly what it will print. Pay close attention to the range() arguments and the if condition.

Then run it to check your answer.

for num in range(1, 8, 2):
if num > 4:
print(f"{num} is big")
else:
print(f"{num} is small")
Exercise 4: Fix the Bug: Letter Counter
Fix the Bug

This code is supposed to count how many times the letter "l" appears in the text "hello world", but it has bugs. Fix the code so it prints:

The letter "l" appears 3 times

Don't change the word variable or the final print statement - fix only the loop logic.

word = "hello world"
count = 0
for char in word:
if char == "L":
count = 1
print(f'The letter "l" appears {count} times')
Exercise 5: Numbered Menu
Write Code

Use enumerate() with start=1 to print a numbered restaurant menu.

Expected output:

1. Burger - $8.99
2. Pizza - $12.50
3. Salad - $7.25
4. Pasta - $10.00
items = ["Burger", "Pizza", "Salad", "Pasta"]
prices = [8.99, 12.50, 7.25, 10.00]
# Use enumerate() and zip() to print the numbered menu
Exercise 6: Reverse a String
Write Code

Use a for loop to reverse the string "Python" by building a new string character by character. Do NOT use slicing ([::-1]) or the reversed() function.

Expected output:

nohtyP
original = "Python"
reversed_str = ""
# Use a for loop to build the reversed string
print(reversed_str)
Exercise 7: Student Grade Report
Write Code

Loop over the grades dictionary and print each student's name and their letter grade. A score of 90+ is "A", 80+ is "B", 70+ is "C", and below 70 is "F".

Expected output:

Alice: 95 (A)
Bob: 82 (B)
Charlie: 67 (F)
Diana: 73 (C)
grades = {"Alice": 95, "Bob": 82, "Charlie": 67, "Diana": 73}
# Loop over the dictionary and print each student's grade
The Biggest Climb
Stretch

A hiking app records the height of the path every few minutes. A climb is a stretch of the path where each height is higher than the one before. Write a function biggest_climb(heights) that returns the most height gained in a single climb, or 0 if the path never goes up.

biggest_climb([100, 120, 115, 130, 160, 150])   # 45

Here the path climbs 20 (100 to 120), drops, then climbs 45 (115 to 160). A step to the same height is not a climb, so it ends the climb before it.

Return the answer instead of printing it: Check calls biggest_climb() with its own paths, some of them hidden.

def biggest_climb(heights):
pass
Solution unlocks after your first Check

Summary: Python For Loops

Here's everything you learned about for loops:

PatternWhat it doesExample
for x in listLoop over each itemfor fruit in fruits:
for i in range(n)Loop n times (0 to n-1)for i in range(5):
range(start, stop, step)Custom number sequencerange(1, 11, 2)
for char in stringLoop over charactersfor c in "hello":
for k, v in dict.items()Loop over key-value pairsfor name, score in grades.items():
enumerate(iterable)Get index + itemfor i, x in enumerate(list):
zip(a, b)Pair items from two listsfor x, y in zip(names, scores):

Key rules to remember:

  • The for line ends with a colon (:)
  • The loop body must be indented
  • range() stops BEFORE the end number
  • enumerate() is better than range(len(...))
  • zip() stops at the shortest list
  • Use singular names for loop variables (for student in students)
  • What's Next?

    For loops are great when you know exactly what you're iterating over. But what if you want to keep looping until some condition changes? That's where while loops come in. In the next tutorial - Python While Loops - you'll learn how to loop based on conditions instead of collections.

    Harder problems

    More problems on this topic: Loops

    Related Tutorials

    Was this tutorial helpful?