A for loop runs the same block of code once for every item in a sequence. In Python it walks over lists, strings, ranges, dictionaries and files directly, with no counter to manage. This lesson covers range(), enumerate(), zip(), break, continue and the little-known for ... else.
In this lesson you will learn
- How to loop over lists and strings
- How
range(start, stop, step)produces numbers - How to get the index too, with
enumerate() - How to loop over two lists together, with
zip() - How
break,continueandelsechange the flow
Looping Over Sequences and Ranges
fruits = ["mango", "guava", "jackfruit"]
for fruit in fruits:
print("I like", fruit)
for ch in "Dhaka":
print(ch, end=" ")
print()
for i in range(1, 6):
print(i, "squared is", i * i)
print(list(range(10, 0, -3)))
Output
I like mango
I like guava
I like jackfruit
D h a k a
1 squared is 1
2 squared is 4
3 squared is 9
4 squared is 16
5 squared is 25
[10, 7, 4, 1]
On each pass the loop variable (fruit, ch, i) takes the next value. print(..., end=" ") replaces the usual newline with a space, so the letters stay on one line.
range() works like this:
range(5)gives 0, 1, 2, 3, 4. The stop value is never included.range(1, 6)starts at 1 and stops before 6.range(10, 0, -3)counts down in steps of 3: 10, 7, 4, 1.
enumerate, zip, break, continue and else
cities = ["Dhaka", "Chattogram", "Khulna"]
for index, city in enumerate(cities, start=1):
print(index, city)
names = ["Rafi", "Nila"]
scores = [88, 93]
for name, score in zip(names, scores):
print(f"{name}: {score}")
numbers = [4, 9, 15, 22, 7]
for n in numbers:
if n % 5 == 0:
print("First multiple of 5:", n)
break
else:
print("No multiple of 5 found")
for n in numbers:
if n % 2:
continue
print("Even:", n)
Output
1 Dhaka
2 Chattogram
3 Khulna
Rafi: 88
Nila: 93
First multiple of 5: 15
Even: 4
Even: 22
enumerate(items, start=1)gives you the position and the item together, which is cleaner thanfor i in range(len(items)).zip(a, b)pairs items from two lists. It stops at the shorter list.breakleaves the loop at once. Here it stops at 15, the first multiple of 5.for ... else: theelseblock runs only when the loop finishes without abreak. It is handy for “search and report not found”.continueskips the rest of the current pass. Odd numbers are skipped, so only 4 and 22 print.
Looping Over a Dictionary
Looping over a dictionary gives its keys. Use .items() to get key and value together:
ages = {"Rafi": 21, "Nila": 19}
for name, age in ages.items():
print(name, age)
More on this in Python Dictionaries.
Common Mistakes
- Expecting
range(1, 5)to include 5. It stops at 4. Userange(1, 6). - Changing a list while looping over it. Removing items during the loop skips elements. Loop over a copy (
for x in items[:]) or build a new list. - Forgetting the colon at the end of the
forline. - Using
range(len(x))everywhere. Loop over the items directly, or useenumerate().
Practice Exercises
Exercise 1. Print the 7 times table from 7 × 1 to 7 × 10.
Show answer
for i in range(1, 11):
print(f"7 x {i} = {7 * i}")
Exercise 2. Count the vowels in "programming in python".
Show answer
count = 0
for ch in "programming in python":
if ch in "aeiou":
count += 1
print(count) # 5
Frequently Asked Questions
What is the difference between a for loop and a while loop?
A for loop runs once per item in a sequence, so you know how many passes there will be. A while loop runs as long as a condition stays true. See Python while Loop.
How do I loop backwards?
Use reversed(items) or range(n - 1, -1, -1).
What is a list comprehension?
A one-line loop that builds a list, such as [n * n for n in range(5)]. It is the short form of a for loop with append().
Summary
for item in sequence:runs once per item.range(start, stop, step)makes number sequences, excludingstop.enumerate()adds an index;zip()walks two lists together.breakexits,continueskips a pass, andelseruns when nobreakhappened.
