Python lambda with if but without else
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]
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]