Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python map function (+ lambda) involving conditionals (if)

Tags:

python

lambda

I'm curious if it's possible to do something with the map()function that I can do via list comprehension.

For ex, take this list comp:

example_list = [x*2 for x in range(5) if x*2/6. != 1]

obviously, this gives me [0, 2, 4, 8].

How do I make the equivalent using the map() function? Doing this gives me a syntax error.

example_map = map(lambda x:x*2 if x*2/6. != 1, range(5))

Just trying to get a better understanding of how to use this function.

like image 893
SpicyClubSauce Avatar asked Jun 11 '15 21:06

SpicyClubSauce


People also ask

How do you write if condition in lambda function in Python?

Using if-else in lambda function Here, if block will be returned when the condition is true, and else block will be returned when the condition is false. Here, the lambda function will return statement1 when if the condition is true and return statement2 when if the condition is false.

Can we use if statement in lambda function?

Since a lambda function must have a return value for every valid input, we cannot define it with if but without else as we are not specifying what will we return if the if-condition will be false i.e. its else part.

Can you do Elif in lambda?

Technically we cannot use an elif statement in a lambda expression.


2 Answers

You'll have to wrap the map around a filter around the list:

example_map = map(lambda x: x*2, filter(lambda x: x*2/6. != 1, range(5)))
like image 163
jwodder Avatar answered Oct 02 '22 22:10

jwodder


Alternatively, you could filter your map rather than maping your filter.

example_map = filter(lambda x: x/6. != 1, map(lambda x: x*2, range(5)))

Just remember that you're now filtering the RESULT rather than the original (i.e. lambda x: x/6. != 1 instead of lambda x: x*2/6. != 1 since x is already doubled from the map)

Heck if you really want, you could kind of throw it all together with a conditional expression

example_map = map(lambda x: x*2 if x*2/6. != 1 else None, range(5))

But it'll leave you with [0, 2, 4, None, 8]. filter(None, example_map) will drop the Nones and leave you [0, 2, 4, 8] as expected.

like image 45
Adam Smith Avatar answered Oct 03 '22 00:10

Adam Smith