You can't use statements in a lambda, only expressions. In addition, your isinstance()
calls are wrong too.
In this case, you only need a boolean expression anyway:
final_list = filter(lambda x: not (isinstance(x, (int, float)) and x < 5), another_list)
This'll only return False if both tests are true, so x
is a number (integer or float) and is smaller than 5. True
is returned otherwise. That means that any value that is not an int or float, or is 5 or greater, is included in the output.
If you invert the numeric test (return true for numbers 5 or over), the test becomes a little more readable:
final_list = filter(lambda x: not isinstance(x, (int, float)) or x >= 5, another_list)
In the general case, you could have used a conditional expression; remember that an expression must produce a value. An if
statement doesn't have to have an else
branch, but that won't do in an expression. In your case your lambda
must return a value to filter by, so you'd use
True if not isinstance(x, (float, int)) else False if x < 5 else True
but both isinstance()
and the <
comparison operator already produce a boolean result.
Instead of a lambda, it may be easier to use a separate function instead, to write out your condition in separate steps:
def everything_except_numbers_under_five(obj):
# allow anything that is not a number
if not isinstance(obj, (int, float)):
return True
# allow only numbers 5 or over
return obj >= 5
final_list = filter(everything_except_numbers_under_five, another_list)