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]
>>> 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]
>>> 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]
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
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
if/else in a list comprehension?
Recommended Posts