for loop
A for loop runs the same block of code once for every item in a list, string, range or any other collection.
for item in iterable:
# code that uses item
else:
# optional: runs if the loop did not breakA for loop walks through a collection one item at a time. On each round, the loop variable (the name after for) holds the next item, and the indented block below runs with it.
Anything you can step through works: lists, strings (one character at a time), dictionaries (their keys), files (one line at a time) and range() for counting.
Python's for is not a counter like in C or JavaScript. If you need the position too, use enumerate() instead of counting by hand.
Examples
1Loop over a list
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print("I like", fruit)I like apple I like banana I like cherry
2Count with range()
range(1, 6) gives the numbers 1 to 5: the end number is not included.
for n in range(1, 6):
print(n, "x 3 =", n * 3)1 x 3 = 3 2 x 3 = 6 3 x 3 = 9 4 x 3 = 12 5 x 3 = 15
3Get the position too with enumerate()
runners = ["Lena", "Omar", "Yuki"]
for place, name in enumerate(runners, start=1):
print(f"{place}. {name}")1. Lena 2. Omar 3. Yuki
4Loop over a dictionary
stock = {"pens": 40, "notebooks": 12, "folders": 0}
for item, count in stock.items():
if count == 0:
print(item, "- sold out")
else:
print(item, "-", count, "left")pens - 40 left notebooks - 12 left folders - sold out
5Stop early with break, and for ... else
break leaves the loop at once. The else block runs only when the loop finished without a break.
orders = [120, 45, 980, 60]
for amount in orders:
if amount > 500:
print("Big order found:", amount)
break
else:
print("No big orders")Big order found: 980
Common mistakes
Changing a list while looping over it
Removing items from the list you are looping over makes the loop skip items. Loop over a copy, or build a new list.
nums = [1, 2, 2, 3]
for n in nums:
if n == 2:
nums.remove(n)
print(nums)
nums = [1, 2, 2, 3]
nums = [n for n in nums if n != 2]
print(nums)[1, 2, 3] [1, 3]
Forgetting the colon or the indent
The line with for must end with :, and every line of the loop body must be indented by the same amount (4 spaces is the standard). Otherwise Python stops with a SyntaxError or IndentationError before running anything.
Questions people ask
How do I loop a fixed number of times?
Use for _ in range(10):. The _ is a common name for a variable you do not need.
How do I loop over two lists at the same time?
Use zip(): for name, score in zip(names, scores):.
How do I loop backwards?
Use reversed(): for x in reversed(items):, or range(10, 0, -1) to count down.
What is the difference between for and while?
for goes through a collection you already have. while loop repeats as long as a condition is true, for when you do not know in advance how many rounds you need.