Python Inline For Loop With If (List Comprehension Examples)
Python inline for loop with if: write a list comprehension, put if after for to filter, or if/else before for to transform elements.
A Python inline for loop is a list comprehension. Wrap the loop in square brackets:
my_list = [1, 2, 3]
[elem for elem in my_list]
# [1, 2, 3]
A bare one-line for is a syntax error—the for statement needs a colon and an indented body:
>>> for elem in my_list
File "<stdin>", line 1
for elem in my_list
^
SyntaxError: invalid syntax
Once the basic form is clear, conditions go in one of two places—and they mean different things. The deeper treatment of both placements is in list comprehensions with if/else.
if after for: filter the list
A condition after the for keeps only elements that pass the test. The result can be shorter than the input:
my_list = [1, 2, 3]
[elem for elem in my_list if elem % 2 != 0]
# [1, 3]
Read it as: “for each elem in my_list, include elem only if it is odd.”
No else is allowed after a trailing filter. If you need both outcomes, use the form in the next section.
if/else before for: transform every element
A condition before the for is a conditional expression. It maps each element to one of two values. The result has the same length as the input:
my_list = [1, 2, 3]
[elem if elem % 2 != 0 else None for elem in my_list]
# [1, None, 3]
The else branch is required. Leaving it out is a syntax error:
>>> [elem if elem % 2 != 0 for elem in my_list]
File "<stdin>", line 1
[elem if elem % 2 != 0 for elem in my_list]
^
SyntaxError: invalid syntax
The valid shape is always:
value_if_true if condition else value_if_false
Filter versus transform
| Placement | Role | Result size |
|---|---|---|
if after for | Filter which elements are kept | Same or smaller |
if/else before for | Transform each element | Same as input |
scores = [45, 82, 90, 58]
# Filter: only passing scores
[s for s in scores if s >= 60]
# [82, 90]
# Transform: label every score
["pass" if s >= 60 else "fail" for s in scores]
# ['fail', 'pass', 'pass', 'fail']
You can combine both: filter first with a trailing if, then transform what remains with a leading if/else. Patterns for that, nested outcomes and multiple conditions are covered in list comprehensions with if/else.
Quick reference
# Basic inline loop
[x for x in items]
# Filter
[x for x in items if condition]
# Transform
[a if condition else b for x in items]
# Filter then transform
[a if c1 else b for x in items if c2]
Use a plain for loop when the body has side effects, several statements or early break/return. Use a comprehension when you are building a new list from an existing iterable.