Use if and else in a Python list comprehension

Place a conditional expression before for to transform values, or a trailing if after for to filter them out.

Best practices
Python programming and application logging

A conditional expression before for chooses a value for each included item. A trailing if after for decides whether that item is included at all.

Transform each item

numbers = [1, 2, 3, 4, 5]
result = [x if x % 2 == 0 else x * 2 for x in numbers]
print(result)  # [2, 2, 6, 4, 10]

Here every input item produces one output value. The expression retains even numbers and doubles odd numbers.

Filter items

evens = [x for x in numbers if x % 2 == 0]
print(evens)  # [2, 4]

This omits items that fail the condition. No else belongs to the filtering clause.

Filter first, then choose a result

To square only the even values:

squares = [x ** 2 for x in numbers if x % 2 == 0]
print(squares)  # [4, 16]

[x ** 2 if x % 2 == 0 else None for x in numbers] is valid Python, but produces a None placeholder for each odd number. It does not remove those items.

You can combine a filter with a genuine two-way transformation:

values = [-2, 0, 1, 2, 3]
labels = ["even" if x % 2 == 0 else "odd" for x in values if x > 0]
print(labels)  # ['odd', 'even', 'odd']

For each value, the trailing x > 0 filter is tested before the result expression. Only accepted items reach the even/odd choice.

FAQ

Can I use multiple filtering conditions? Yes. [x for x in values if x > 0 if x % 2 == 0] is equivalent here to using if x > 0 and x % 2 == 0. The conditions are evaluated from left to right with short-circuiting.

Can I nest conditional expressions? Yes, but several branches are often clearer in a helper function or an ordinary loop. Keep the expression small enough that its output and filtering rules remain obvious.

Does filtering always shorten the result? It may keep all, some, or none of the items. In this single-loop example it cannot increase the number of output items. Nested loops have different cardinality, so keep that assumption scoped to the simple case.

References

Get a tailored plan

Contact us

Join the community

Scan with WeChat
to join the community

Try Guance

Start online and pay only for what you use.

Get started

Choose a Guance plan

Code hosting