[PYTHON] If ... else in comprehension

If there is an if ... else statement in the list comprehension (https://docs.python.org/ja/3.7/tutorial/datastructures.html#list-comprehensions), beginners are confused about the order in which the code is read. I think there are times.

>>> x = [8,1,7,2,6,3,5,4]

Inclusive notation if

>>> l1 = [i for i in x if i > 5]
>>> l1
[8, 7, 6]

Here ʻif i> 5` is part of the comprehension. Equivalent to the following code:

>>> l1 = []
>>> for i in x:
...     if i > 5:
...             l1.append(i)
...
>>> l1
[8, 7, 6]

If ... else in comprehension

>>> l2 = [i if i > 5 else 0 for i in x]
>>> l2
[8, 0, 7, 0, 6, 0, 0, 0]

Here, ʻi if i> 5 else 0` is not a comprehension syntax. Equivalent to the following code:

>>> l2 = []
>>> for i in x:
...     l2.append(i if i > 5 else 0)
...
>>> l2
[8, 0, 7, 0, 6, 0, 0, 0]

Conditional expression

The above ʻi if i> 5 else 0` is an operation called conditional expression.

>>> i = 6
>>> i if i > 5 else 0
6
>>> i = 4
>>> i if i > 5 else 0
0

By the way

If there is no else in the conditional expression, you will get angry.

>>> i = 6
>>> i if i > 5
  File "<stdin>", line 1
    i if i > 5
             ^
SyntaxError: invalid syntax

So Even if you write as follows, you will get angry as well.

>>> l3 = [i if i > 5 for i in x]
  File "<stdin>", line 1
    l3 = [i if i > 5 for i in x]
                       ^
SyntaxError: invalid syntax

reference

if/else in a list comprehension?

Recommended Posts

If ... else in comprehension
FizzBuzz in list comprehension
[Road to intermediate Python] Use if statement in list comprehension
Judgment of if by list comprehension
I want to print in a comprehension
Check if the URL exists in Python
Python / dictionary> setdefault ()> Add if not in dictionary