Skip to main content

Python For Loops: Iterate Over Anything with Examples

Beginner25 min7 exercises95 XP
0/7 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
Loading editor...

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
Loading editor...

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
Loading editor...

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
Loading editor...

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
Loading editor...

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
Loading editor...

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
Loading editor...

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
Loading editor...

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
Loading editor...

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()
Loading editor...

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
Loading editor...

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
Loading editor...

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
Loading editor...
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
Loading editor...
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.

Loading editor...
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 word "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 — just fix the loop logic.

Loading editor...
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
Loading editor...
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
Loading editor...
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)
Loading editor...

Summary: Python For Loops

Here's everything you learned about for loops:
---------
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](/python/python-while-loops) — you'll learn how to loop based on conditions instead of collections.