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
— step through the idea, then dive into the details below.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.
#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.
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)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.
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.
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)stoprange(start, stop)— counts fromstartup to (but not including)stoprange(start, stop, step)— counts fromstarttostop, jumping bystep
# Count from 0 to 4
for i in range(5):
print(i)# Count from 1 to 5
for i in range(1, 6):
print(i)# Count by twos
for i in range(0, 10, 2):
print(i)range() stops BEFORE the end number
A very common beginner mistake: range(5) gives you 0, 1, 2, 3, 4 — not 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.
numbers = [3, 7, 2, 9, 4]
total = 0
for num in numbers:
total = total + num
print("Sum:", total)# 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.
colors = ["red", "green", "blue"]
for index, color in enumerate(colors):
print(index, color)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.
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.
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.
What does this code print?
for i in range(1, 6, 2):
print(i)This code is supposed to print each fruit in the list, but it has a bug. What is wrong?
fruits = ["apple", "banana", "cherry"]
for fruit in fruits
print(fruit)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)
Put these lines in the right order to add up all numbers in the list and print the total.
total = total + num
numbers = [4, 7, 2, 5]
for num in numbers:
total = 0
print("Total:", total)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: