Search code examples
pythonpython-3.xconditional-operator

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

  • Aside from [x if x%2 == 0 else 0 for x in range(10)] being shorter, you can use a lambda, but you must call it.

    Either with a default arg (x=x):

    [x if (lambda x=x: x%2 ==0)() else 0 for x in range(10)]
    

    or by explicitely passing x:

    [x if (lambda x: x%2 ==0)(x) else 0 for x in range(10)]
    

    Result for either case:

    [0, 0, 2, 0, 4, 0, 6, 0, 8, 0]