A for
loop lets you iterate over a sequence of values. In Python, the sequence can be a
list, tuple, string, range, dictionary, or any iterable.
Basic idea
In a for
loop you specify a loop variable and an iterable to step through:
for item in iterable:
# use item inside the loop
Example 1 — Tuple of colours
Here the loop variable color
takes each value from a tuple:
for color in ('red', 'orange', 'yellow', 'green', 'cyan', 'blue', 'violet'):
print(color)
Example 2 — Numbering items with enumerate
Instead of manually updating a counter, use enumerate
to get the index (starting at 1) and the value:
colors = ('red', 'orange', 'yellow', 'green', 'cyan', 'blue', 'violet')
for i, color in enumerate(colors, start=1):
print(f"{i}-th color of the rainbow is {color}")
Example 3 — Different types in one iterable
The items in a sequence can be of mixed types:
for item in (1, 2, 3, 'one', 'two', 'three'):
print(item)
Example 4 — Looping over a range
range(start, stop, step)
generates a sequence of integers:
for n in range(1, 6): # 1, 2, 3, 4, 5
print(n)
Example 5 — Strings are iterable
Iterating over a string yields its characters:
for ch in "Python":
print(ch)
Example 6 — Dictionaries
Use .items()
to get key–value pairs:
capitals = {"UK": "London", "France": "Paris", "Japan": "Tokyo"}
for country, city in capitals.items():
print(f"{city} is the capital of {country}")
Example 7 — break
, continue
, and for…else
break
exits the loop early; continue
skips to the next iteration.
The optional else
block runs only if the loop wasn’t terminated by break
.
numbers = [2, 4, 6, 9, 12]
for x in numbers:
if x % 2 != 0:
print("Found an odd number:", x)
break
else:
print("All numbers were even") # runs only if no break happened
Example 8 — List comprehension (compact looping)
A concise way to build lists from a loop:
squares_of_evens = [n*n for n in range(1, 11) if n % 2 == 0]
print(squares_of_evens) # [4, 16, 36, 64, 100]
Key takeaways: use for
to iterate over any iterable; prefer enumerate
for counters; use range
for integer sequences; and remember control tools like break
, continue
, and for…else
.