Anurag Gupta
Anurag Gupta

Reputation: 31

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.

Upvotes: 0

Views: 922

Answers (3)

Mike Scotty
Mike Scotty

Reputation: 10782

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]

Upvotes: 3

Red
Red

Reputation: 27567

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]

Upvotes: 1

lcdumort
lcdumort

Reputation: 611

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)

Upvotes: 0

Related Questions