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 i
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]