Control FlowBeginner8 min28 / 63

for Loops

Learn how to repeat actions over lists, strings, and ranges using Python's for loop — the workhorse of everyday Python code.

Imagine you have a grocery list with 10 items, and you need to read each one aloud. You wouldn't write 10 separate instructions — you'd just say "go through the list, one item at a time." That's exactly what a for loop does in Python.

A for loop lets you visit every item in a collection and do something with it. It's one of the most useful things you'll ever learn in programming.

See it in action

Visual walkthrough1 / 6
1

Stop Repeating Yourself

A for loop lets Python do repetitive work for you — visit every item in a collection and do something with it. Write the action once; Python runs it for every item.

For loops are one of the most-used tools in all of Python.

#Your First for Loop

The basic structure is: for item in collection: followed by indented code. Python will run that indented code once for each item, automatically moving to the next one each time.

The loop visits each item in the list, one at a time.
fruits = ["apple", "banana", "cherry"]

for fruit in fruits:
    print(fruit)
Think of it like

Think of a for loop like a conveyor belt

Picture a conveyor belt at a supermarket checkout. Each item slides up to you one at a time. You scan it, then it moves on and the next item arrives. The for loop is Python's conveyor belt — it hands you each item in the collection, one by one, until there are none left.

#The Loop Variable

The word between for and in is called the loop variable. It holds the current item on each pass through the loop. You can name it anything — but a descriptive name (like fruit for a list of fruits) makes your code much easier to read.

The loop variable changes automatically each time — you never have to update it yourself.

You can use the loop variable in any expression inside the loop.
temperatures = [72, 68, 75, 80, 65]

for temp in temperatures:
    if temp > 73:
        print(temp, "is warm")
    else:
        print(temp, "is cool")

#Looping Over a String

A string is just a sequence of characters. You can loop over it the same way you loop over a list — Python will hand you one character at a time.

Each character in the string gets its own loop iteration.
word = "hello"

for letter in word:
    print(letter)

#Counting with range()

Sometimes you just want to repeat something a set number of times, or count through numbers. The built-in range() function creates a sequence of numbers for you to loop over.

  • range(stop) — counts from 0 up to (but not including) stop
  • range(start, stop) — counts from start up to (but not including) stop
  • range(start, stop, step) — counts from start to stop, jumping by step
range(5) gives you 0, 1, 2, 3, 4 — five numbers starting from zero.
# Count from 0 to 4
for i in range(5):
    print(i)
range(1, 6) starts at 1 and stops before 6.
# Count from 1 to 5
for i in range(1, 6):
    print(i)
The third argument is the step — how much to jump each time.
# Count by twos
for i in range(0, 10, 2):
    print(i)
Common mistake

range() stops BEFORE the end number

A very common beginner mistake: range(5) gives you 0, 1, 2, 3, 4not 0, 1, 2, 3, 4, 5. The stop value is always excluded. If you want to include 5, write range(6) or range(1, 6).

#Building Results in a Loop

One of the most powerful patterns in programming is accumulating a result inside a loop. You start with an empty container (or zero), and add to it with each pass through the loop.

Start with total = 0, then add each number as the loop runs.
numbers = [3, 7, 2, 9, 4]
total = 0

for num in numbers:
    total = total + num

print("Sum:", total)
Start with an empty list and append items that pass a condition.
# Collect only even numbers into a new list
numbers = [1, 2, 3, 4, 5, 6, 7, 8]
evens = []

for num in numbers:
    if num % 2 == 0:
        evens.append(num)

print(evens)

#Getting Index and Value with enumerate()

Sometimes you need to know both the position of an item and its value. The enumerate() function gives you both at once, as a pair of values you can unpack into two variables.

enumerate() pairs each item with its position number.
colors = ["red", "green", "blue"]

for index, color in enumerate(colors):
    print(index, color)
Tip

Use enumerate() instead of range(len(...))

New Python learners sometimes write for i in range(len(my_list)): to get an index. That works, but enumerate() is cleaner and more Pythonic. It's easier to read and less likely to cause off-by-one mistakes.

#Looping Over a Dictionary

Dictionaries store key-value pairs. When you loop over a dictionary, Python gives you the keys by default. Use .values() to loop over values, or .items() to get both the key and value together.

.items() gives you each key-value pair as a tuple you can unpack.
scores = {"Alice": 92, "Bob": 85, "Carol": 78}

# Loop over keys and values together
for name, score in scores.items():
    print(name, "scored", score)

#When Should You Use a for Loop?

Use a for loop when: - You have a known collection to work through (a list, string, dictionary, range of numbers) - You want to process, filter, or transform every item - You want to build up a result by looking at each item one at a time

If you don't know in advance how many times you'll loop, a while loop (a later lesson) is the better fit.

Quick check

What does range(2, 8, 2) produce?

Key takeaways

  • A for loop visits each item in a collection one at a time — list, string, range, or dictionary.
  • range(stop), range(start, stop), and range(start, stop, step) let you loop over numbers without making a list.
  • The loop variable holds the current item on each pass — name it something descriptive.
  • Use enumerate() when you need both the index and the value of each item.
  • Accumulate results by starting with an empty list or zero, then building up inside the loop.
Practice challenges
Test yourself · earn XP
0/4
Predict the output#1

What does this code print?

predict-output
for i in range(1, 6, 2):
    print(i)
Fix the bug#2

This code is supposed to print each fruit in the list, but it has a bug. What is wrong?

fix-bug
fruits = ["apple", "banana", "cherry"]

for fruit in fruits
    print(fruit)
Fill in the blank#3

Complete the code so it prints the index and color together, like: 0 red

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

for index, color in (colors):
    print(index, color)
Reorder the lines#4

Put these lines in the right order to add up all numbers in the list and print the total.

1
    total = total + num
2
numbers = [4, 7, 2, 5]
3
for num in numbers:
4
total = 0
5
print("Total:", total)
Your turn
Practice exercise

Write a program that loops over a list of five words and prints each word along with how many letters it contains. For example, for the word "cat" it should print: cat has 3 letters

Try it live — edit the code and hit Run to execute real Python:

solution.py · editable