Wednesday, May 14, 2025
HomePythonUtilizing "else" in a comprehension

Utilizing “else” in a comprehension


Python’s record comprehensions can have an non-obligatory situation on the finish to filter down outcomes, utilizing the if key phrase.

However what in case you do not wish to filter down outcomes, however as an alternative you’d wish to have one expression evaluated or one other?

Can a comprehension use an if with an else?

Do record comprehensions help else?

This record comprehension is not legitimate:

>>> counts = [2, -1, 4, 7, -3, 6]
>>> sanitized_counts = [n for n in counts if n > 0 else 0]
  File "<stdin>", line 1
    sanitized_counts = [n for n in counts if n > 0 else 0]
                                                   ^^^^
SyntaxError: invalid syntax

Python’s record comprehensions haven’t any help for an else key phrase.

However else does work in comprehensions…

However wait!
I’ve seen else in a comprehension earlier than.

This comprehension works wonderful:

>>> sanitized_counts = [n if n > 0 else 0 for n in counts]

This offers us all the identical numbers as earlier than, however all of the unfavourable numbers are become zeros as an alternative:

>>> counts = [2, -1, 4, 7, -3, 6]
>>> sanitized_counts
[2, 0, 4, 7, 0, 6]

How does that work?

Python’s ternary operator

Effectively, that else is not really a part of the comprehension, and neither is the if.

That is Python’s model of a ternary operator:

>>> n = 5
>>> n if n > 0 else 0
5

This expression checks a situation and evaluates one expression if the situation is truthy, or one other expression if the situation is falsey:

>>> n = -3
>>> n if n > 0 else 0
0

These are typically referred to as inline if expressions or conditional expressions.

That is what we noticed in the beginning of our comprehension earlier than:

>>> counts = [2, -1, 4, 7, -3, 6]
>>> sanitized_counts = [n if n > 0 else 0 for n in counts]

Conditional expressions in record comprehension

So the mapping a part of this comprehension has an inline if inside it.

This is the identical comprehension written over a number of strains of code (see breaking code over a number of strains in Python):

>>> sanitized_counts = [
...     n
...     if n > 0
...     else 0
...     for n in counts
... ]

These first three strains are not a part of the comprehension syntax, however are as an alternative a single expression that occurs to be inside our comprehension.

Making extra readable record comprehensions

I usually favor to write down my record comprehensions over a number of strains of code.

However this comprehension is somewhat bit misleading as a result of it appears like every element of our inline if is definitely a part of our comprehension syntax:

>>> sanitized_counts = [
...     n
...     if n > 0
...     else 0
...     for n in counts
... ]

We might make this a bit extra readable by placing all three parts of that conditional expression on one line:

>>> sanitized_counts = [
...     n if n > 0 else 0
...     for n in counts
... ]

I would favor to take this even additional by wrapping parentheses round that first expression, to make it clearer that it isn’t really a part of the comprehension syntax itself:

>>> sanitized_counts = [
...     (n if n > 0 else 0)
...     for n in counts
... ]

People studying our code who’ve by no means seen an inline if embedded in a comprehension will in all probability discover this a bit simpler to know.

Keep away from complicated comprehensions

Easier comprehensions are sometimes simpler to learn than extra complicated ones.

So we’d even think about transferring that first conditional expression out of our comprehension and into its personal operate:

>>> def negatives_to_zero(n):
...     return n if n > 0 else 0
...
>>> sanitized_counts = [negatives_to_zero(n) for n in counts]

Generally an inline if is readable sufficient.
However the extra complicated they’re, the extra I would hesitate to embed them inside a bigger expression.

Python’s record comprehensions and ifelse

Python’s record comprehensions do not help the else key phrase.
However there’s nothing stopping us from embedding a conditional expression inside a comprehension.

Simply preserve readability in thoughts while you’re embedding a big expression inside a comprehension.

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments