To run code only for some items, put an if statement inside the for loop, indented one level deeper: for n in numbers: then if n > 10: then the code to run. The condition is checked on every pass through the loop, so only items that pass it are processed.
numbers = [3, 8, 15, 22, 7]
for n in numbers:
if n > 10:
print(n)
Example output:
15
22
Everything below builds on that shape: add elif and else branches, skip items with continue, stop early with break, and use the loop's own else clause. The examples were checked against the behaviour described in the Python documentation for Python 3.
How a for loop with an if statement runs
A for statement takes each item of a sequence in order and assigns it to the loop variable. According to the Python tutorial, it iterates over the items of any sequence, such as a list or a string, in the order they appear. The body of the loop is the indented block under the for line. When you put an if in that body, Python evaluates its condition fresh for each item.
Indentation decides what belongs where. In the first example the print is indented under the if, so it runs only when the condition is true. If you moved print(n) back to the same level as the if, it would run for every item, and the if would have no visible effect.
Use elif and else for more than one outcome
An if statement can carry any number of elif branches and one final else. The language reference says Python evaluates the conditions one by one until one is true, runs only that branch, and runs the else branch only if every condition was false. Inside a loop this gives each item exactly one outcome:
scores = [92, 74, 58, 85]
for score in scores:
if score >= 90:
grade = "A"
elif score >= 70:
grade = "B"
else:
grade = "F"
print(score, grade)
Example output:
92 A
74 B
58 F
85 B
Order matters. Because 92 is also greater than 70, the score >= 90 test must come first, or every passing score would get a B.
Combine conditions with and, or and not
One if can test several things. Use and when all parts must be true, or when any part is enough, and not to flip a test. The full list of comparison and boolean operators is in Python operators explained.
for n in range(1, 21):
if n % 2 == 0 and n % 3 == 0:
print(n, "is divisible by 2 and 3")
Example output:
6 is divisible by 2 and 3
12 is divisible by 2 and 3
18 is divisible by 2 and 3
Remember that range(1, 21) stops before 21. The Python tutorial states that the end point is never part of the generated sequence.
Loop over strings, dictionaries and indexes
The same pattern works for any iterable. For a string, the loop variable is one character at a time:
vowels = 0
for letter in "python for loop":
if letter in "aeiou":
vowels += 1
print(vowels)
Example output:
4
The string has four vowels: the o in "python", the o in "for", and the two os in "loop". For a dictionary, .items() gives you key and value together, so the condition can use either:
prices = {"pen": 1.5, "notebook": 4.0, "stapler": 9.0}
for item, price in prices.items():
if price < 5:
print(item, "costs", price)
Example output:
pen costs 1.5
notebook costs 4.0
If you need the position of each item as well, wrap the list in enumerate(): for index, value in enumerate(values):. Then a test such as if index % 2 == 0: picks every other item.
Skip items with continue
When the interesting work comes after a filter, continue keeps the code flat. The tutorial describes it as continuing with the next iteration of the loop. This is the example it uses, with its output:
for num in range(2, 10):
if num % 2 == 0:
print(f"Found an even number {num}")
continue
print(f"Found an odd number {num}")
Example output (first lines):
Found an even number 2
Found an odd number 3
Found an even number 4
Found an odd number 5
A common use is a guard clause at the top of the loop: if not line.strip(): continue skips blank lines, and the rest of the body can assume a real line. That avoids wrapping the whole body in one big if.
Stop early with break
The break statement ends the innermost enclosing for or while loop at once. Use it when you only need the first match:
names = ["ana", "li", "omar", "eve"]
for name in names:
if len(name) > 3:
print("First long name:", name)
break
Example output:
First long name: omar
With nested loops, break leaves only the inner loop. The outer loop keeps going. For more on nesting, see nested for loops explained.
The for-else clause: run code when nothing matched
A for loop can have its own else block. Per the tutorial, if the loop finishes without executing break, the else clause runs, and if a break ends the loop, it is skipped. That makes it a natural "not found" branch for a search:
for n in range(2, 10):
for x in range(2, n):
if n % x == 0:
print(n, "equals", x, "*", n // x)
break
else:
print(n, "is a prime number")
Example output (this is the tutorial's own prime-number example):
2 is a prime number
3 is a prime number
4 equals 2 * 2
5 is a prime number
6 equals 2 * 3
7 is a prime number
8 equals 2 * 4
9 equals 3 * 3
Look at the indentation: the else lines up with the inner for, not with the if. The tutorial calls this out explicitly, because it is the part people misread. An else lined up with if would run for every x that is not a factor, which gives a very different result.
Two details from the language reference are worth knowing. A continue does not stop the else from running, because the loop still reaches the end of its items. And leaving the loop with return or an exception also skips the else.
One-line version: a list comprehension with if
When the loop exists only to build a new list from items that pass a test, a comprehension does it in one line:
numbers = [3, 8, 15, 22, 7]
big = [n for n in numbers if n > 10]
print(big)
Example output:
[15, 22]
The list comprehension guide covers the full syntax, including the if/else form that goes before the for. If the body does something else, such as printing or writing to a file, keep the ordinary loop.
Common mistakes
- Missing colon. Both
forandiflines must end with:. Without it Python raisesSyntaxError: expected ':'in recent versions. - Wrong indentation. The body must be indented, and the levels must be consistent. See IndentationError in Python for the exact messages and fixes.
=instead of==. A single=assigns, and inside anifcondition it is a syntax error. Compare with==.- Removing items from the list you are looping over. The loop tracks a position, so deleting an item shifts the rest and the next item is skipped. You can reproduce this: with
nums = [2, 4, 6], the loopfor n in nums: if n % 2 == 0: nums.remove(n)leaves[4], even though every number is even. Loop over a copy (for n in nums[:]:) or build a new list instead. - Using the loop variable after an empty loop. If the sequence is empty, the loop variable is never assigned, and reading it later raises
NameError. Initialise any result variable before the loop.
When a while loop fits better
If you do not know in advance how many iterations you need, and the stopping point depends on a condition rather than a sequence, use while. The trade-offs are laid out in for loop vs while loop.
Frequently asked questions
- Can I put an if statement inside a for loop in Python?
- Yes. Indent the if block one level deeper than the for line. The if condition is evaluated once per iteration, using the current value of the loop variable, so only the items that satisfy it run the indented code.
- What is the difference between continue and break inside a for loop?
- continue skips the rest of the current iteration and moves on to the next item. break ends the whole loop immediately. Code after the loop then runs, and a for-else clause is skipped.
- Does the else in a for loop belong to the if?
- No. An else that is indented to line up with for belongs to the loop. It runs when the loop finishes all its items without hitting break. An else lined up with if belongs to that if and runs on every iteration where the condition is false.
- How do I write a for loop with an if condition on one line?
- Use a list comprehension, for example [n for n in numbers if n > 10]. This builds a new list of the items that pass the test. For loops that do something other than build a list, the multi-line form is clearer.