for Statement
Python's for statement iterates over each element of a sequence (list, tuple, string, range) in order. Indentation defines the block boundaries, and any iterable value can be traversed.
Syntax
# Basic syntax
for variable in iterable:
# processing executed for each element
# Looping a specified number of times with range()
for i in range(count):
# i starts at 0 and goes up to count-1.
# break exits the loop early.
for variable in iterable:
if condition:
break
# continue skips the current iteration.
for variable in iterable:
if condition:
continue
# else clause: executed when the loop completes without break.
for variable in iterable:
processing
else:
# executed only when the loop ran to completion.
Keywords / Functions Reference
| Syntax / Function | Notes |
|---|---|
| for variable in iterable: | Assigns each element of the iterable to the variable and repeats the block. |
| range(stop) | Generates integers from 0 up to (but not including) stop. The stop value itself is not included. |
| range(start, stop) | Generates integers from start up to (but not including) stop. |
| range(start, stop, step) | Generates integers at step intervals. A negative step produces a reverse sequence. |
| break | Immediately terminates the loop. The for's else clause is skipped. |
| continue | Skips the remaining processing and moves to the next iteration. |
| for ... else: | Executes the else block when the loop completes without being broken by break. |
Sample Code
Iterating over each element of a list in order. A sample displaying a list of Yakuza character names.
characters.py
# Define a list of major Yakuza characters.
characters = ["Kiryu Kazuma", "Majima Goro", "Nishikiyama Akira", "Date Makoto"]
# Use a for loop to take out each element of the list in order.
for name in characters:
print(name)
python3 characters.py Kiryu Kazuma Majima Goro Nishikiyama Akira Date Makoto
Looping a specified number of times with range(). Checking start / stop / step argument variations.
range_variants.py
# range(stop): repeats from 0 to stop-1.
print("--- range(5) ---")
for i in range(5):
print(i, end=" ")
print()
# range(start, stop): repeats from start to stop-1.
print("--- range(1, 6) ---")
for i in range(1, 6):
print(i, end=" ")
print()
# range(start, stop, step): repeats at step intervals.
print("--- range(0, 10, 2) ---")
for i in range(0, 10, 2):
print(i, end=" ")
print()
# A negative step produces a reverse sequence.
print("--- range(5, 0, -1) ---")
for i in range(5, 0, -1):
print(i, end=" ")
print()
python3 range_variants.py --- range(5) --- 0 1 2 3 4 --- range(1, 6) --- 1 2 3 4 5 --- range(0, 10, 2) --- 0 2 4 6 8 --- range(5, 0, -1) --- 5 4 3 2 1
Strings and tuples can also be traversed with a for loop. The same syntax works for any iterable.
string_tuple.py
# A string can be iterated one character at a time.
name = "Kiryu"
for ch in name:
print(ch)
# Tuples can also be traversed with a for loop.
substories = ("Billiards", "Karaoke", "Mahjong", "Shogi")
for substory in substories:
print("Substory:", substory)
python3 string_tuple.py K i r y u Substory: Billiards Substory: Karaoke Substory: Mahjong Substory: Shogi
Processing two-dimensional data with nested loops. A sample displaying teams and their members.
nested_loop.py
# A dictionary grouping Yakuza organizations and their members.
clans = {
"Omi Alliance": ["Arakawa Masumi", "Saejima Taiga"],
"Tojo Clan": ["Kiryu Kazuma", "Nishikiyama Akira"],
}
# The outer loop extracts organization names; the inner loop extracts members.
for clan_name, members in clans.items():
print("[" + clan_name + "]")
for member in members:
print(" -", member)
python3 nested_loop.py [Omi Alliance] - Arakawa Masumi - Saejima Taiga [Tojo Clan] - Kiryu Kazuma - Nishikiyama Akira
Exiting a loop early with break. A sample that stops searching the moment a target element is found.
break_example.py
# Searching for a specific character in a list of Yakuza bosses.
bosses = ["Shimano Futoshi", "Majima Goro", "Nishikiyama Akira", "Terada Yukio"]
target = "Nishikiyama Akira"
# break: immediately ends the loop when the target is found.
for boss in bosses:
if boss == target:
print(target, "found")
break
print(boss, "is not the target")
else:
# Executed when break did not occur (target not found).
print(target, "was not found")
python3 break_example.py Shimano Futoshi is not the target Majima Goro is not the target Nishikiyama Akira found
Skipping specific elements with continue. Used when only elements that don't meet the condition should be processed.
continue_example.py
# Skip and display characters below a power threshold.
fighters = [
("Kiryu Kazuma", 98),
("Majima Goro", 97),
("Saejima Taiga", 85),
("Shinada Tatsuo", 60),
]
threshold = 80
for name, power in fighters:
# Skip if power is below the threshold.
if power < threshold:
continue
print(f"{name} (Power: {power}) is eligible")
python3 continue_example.py Kiryu Kazuma (Power: 98) is eligible Majima Goro (Power: 97) is eligible Saejima Taiga (Power: 85) is eligible
For loop behavior with dicts and sets. Dicts are traversed by keys by default.
dict_set_loop.py
# Passing a dict directly to a for loop traverses "keys".
profile = {"name": "Kiryu Kazuma", "age": 27, "hometown": "Kamurocho"}
print("--- Keys only ---")
for key in profile:
print(key)
print("--- Keys and values ---")
# Use items() to get key-value pairs at the same time.
for key, value in profile.items():
print(f"{key}: {value}")
# Sets are traversed in an unspecified order (order is not guaranteed).
print("--- Set ---")
skills = {"Fighting", "Gambling", "Karaoke", "Investing"}
for skill in skills:
print(skill)
python3 dict_set_loop.py --- Keys only --- name age hometown --- Keys and values --- name: Kiryu Kazuma age: 27 hometown: Kamurocho --- Set --- Gambling Karaoke Fighting Investing
Common Mistakes
Common Mistake 1: Modifying a list during iteration
Modifying the list being iterated directly can cause elements to be skipped or other unexpected behavior. When removing or adding elements, iterate over a copy or use a list comprehension.
ng_modify_list.py
# NG: removing an element from the list being iterated causes elements to be skipped.
members = ["Kiryu Kazuma", "Majima Goro", "Nishikiyama Akira", "Date Makoto"]
for member in members:
if member == "Nishikiyama Akira":
members.remove(member)
print(members)
python3 ng_modify_list.py ['Kiryu Kazuma', 'Majima Goro', 'Date Makoto']
ok_modify_list.py
# OK: create a new list using list comprehension.
members = ["Kiryu Kazuma", "Majima Goro", "Nishikiyama Akira", "Date Makoto"]
members = [m for m in members if m != "Nishikiyama Akira"]
print(members)
# OK: iterating over a copy and modifying the original is also an option.
members2 = ["Kiryu Kazuma", "Majima Goro", "Nishikiyama Akira", "Date Makoto"]
for member in members2[:]:
if member == "Nishikiyama Akira":
members2.remove(member)
print(members2)
python3 ok_modify_list.py ['Kiryu Kazuma', 'Majima Goro', 'Date Makoto'] ['Kiryu Kazuma', 'Majima Goro', 'Date Makoto']
Common Mistake 2: The stop value of range is not included
range(start, stop) does not include the stop value itself. To generate 5 values from 1 to 5, range(1, 6) must be used.
ng_range_stop.py
# NG: intending to generate 5 numbers from 1 to 5, but 5 is not included.
print("--- range(1, 5) ---")
for i in range(1, 5):
print(i, end=" ")
print()
python3 ng_range_stop.py --- range(1, 5) --- 1 2 3 4
ok_range_stop.py
# OK: set stop to the last desired value + 1.
print("--- range(1, 6) ---")
for i in range(1, 6):
print(i, end=" ")
print()
python3 ok_range_stop.py --- range(1, 6) --- 1 2 3 4 5
Common Mistake 3: Misunderstanding for/else
The else clause of a for loop runs "when the loop completes without being interrupted by break". It does not mean "when the condition was never true".
ng_for_else.py
# Checking the for/else behavior.
bosses = ["Shimano Futoshi", "Majima Goro", "Nishikiyama Akira"]
target = "Date Makoto"
# Since the loop ran to completion without break, else is executed.
for boss in bosses:
if boss == target:
print(target, "found")
break
else:
# This runs not just when target is not found,
# but whenever the loop completes without break.
print(target, "was not found")
python3 ng_for_else.py Date Makoto was not found
ok_for_else.py
# Using for/else correctly.
# When break interrupts the loop, else does not run.
bosses = ["Shimano Futoshi", "Majima Goro", "Nishikiyama Akira", "Date Makoto"]
target = "Date Makoto"
for boss in bosses:
if boss == target:
print(target, "found")
break
else:
print(target, "was not found")
python3 ok_for_else.py Date Makoto found
Notes
Python's for loop is designed so that "anything iterable can be traversed". Lists, tuples, strings, ranges, dicts, sets, file objects — all can be handled with the same syntax. Directly extracting elements without using indices is the Pythonic style.
Passing a dict to a for loop traverses only the keys by default. Use items() to get keys and values together, values() for values only, and keys() to explicitly get keys. See dict.keys() / values() / items() for details.
When index and value are needed at the same time, enumerate() is used more often than range(len(...)). For traversing multiple lists in parallel, zip() is convenient. See range() / enumerate() / zip() for these functions. When a loop generates a new list, rewriting it as a list comprehension can make the code more concise.
If you find any errors or copyright issues, please contact us.