If you use list comprehensions, you can use if to exclude elements that you don't want to include in the resulting list. For example, the following code
[ x for x in [1, 2, 3, ] if x > 2]
This way, the resulting list will only contain 3. At this time, there is a case where the function is applied to x and it is desired to perform filtering by the applied value. For example, the following code
def f(x):
x = x * 2
return x
[ f(x) for x in [1, 2, 3, ] if f(x) > 2]
This way, the resulting list will contain 4, 6. ~~ The important thing is that in these cases method f is only executed once for each element. ~~ -> This part is incorrect.
Recommended Posts