Python lambda with if but without else

PythonLambdaInline If

Python Problem Overview


I was writing some lambda functions and couldn't figure this out. Is there a way to have something like lambda x: x if (x<3) in python? As lambda a,b: a if (a > b) else b works ok. So far lambda x: x < 3 and x or None seems to be the closest i have found.

Python Solutions


Solution 1 - Python

A lambda, like any function, must have a return value.

lambda x: x if (x<3) does not work because it does not specify what to return if not x<3. By default functions return None, so you could do

lambda x: x if (x<3) else None

But perhaps what you are looking for is a list comprehension with an if condition. For example:

In [21]: data = [1, 2, 5, 10, -1]

In [22]: [x for x in data if x < 3]
Out[22]: [1, 2, -1]

Solution 2 - Python

I found that filter provided exactly what I was looking for in python 2:

>>> data = [1, 2, 5, 10, -1]
>>> filter(lambda x: x < 3, data)
[1, 2, -1]

The implementation is different in 2.x and 3.x: while 2.x provides a list, 3.x provides an iterator. Using a list comprehension might make for a cleaner use in 3.x:

>>> data = [1, 2, 5, 10, -1]
>>> [filter(lambda x: x < 3, data)]
[1, 2, -1]

Solution 3 - Python

What's wrong with lambda x: x if x < 3 else None?

Solution 4 - Python

You can always try to invoke 'filter' for conditional checks. Fundamentally, map() has to work on every occurrence of the iterables, so it cannot pick and choose. But filter may help narrow down the choices. For example, I create a list from 1 to 19 but want to create a tuple of squares of only even numbers.

x = list(range(1,20))

y = tuple(map(lambda n: n**2, filter(lambda n: n%2==0,x)))

print (y)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionrootView Question on Stackoverflow
Solution 1 - PythonunutbuView Answer on Stackoverflow
Solution 2 - Pythonim_just_here_to_learnView Answer on Stackoverflow
Solution 3 - Pythonuser4815162342View Answer on Stackoverflow
Solution 4 - PythonTirthaView Answer on Stackoverflow