'Lambda expression in ternary operator
I am trying to write following code but is throwing error:
a = [x if lambda x: x%2 ==0 else 0 for x in range(10)]
print(a)
The error is pointing at lambda statement. Is it illegal to use her? Of yes then why because all my function is returning is the Boolean True or False.
Solution 1:[1]
In order to utilize your lambda function within your list comprehension, simply define a variable to store the function:
func = lambda x: x % 2 == 0
a = [x if func(x) else 0 for x in range(10)]
print(a)
Output:
[0, 0, 2, 0, 4, 0, 6, 0, 8, 0]
Solution 2:[2]
lambda x: x%2 ==0 is a function, not a condition.
Why not use this instead?
a = [x if x%2 == 0 else 0 for x in range(10)]
print(a)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Ann Zen |
| Solution 2 | lcdumort |
