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.
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.
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.
Technically we cannot use an elif statement in a lambda expression.
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)))
Alternatively, you could filter
your map
rather than map
ing 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 None
s and leave you [0, 2, 4, 8]
as expected.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With