In python you can take an array like:
a = [1, 2, 3, 4, 5, 6]
...and then run the following list comprehension to evaluate True for elements based on a conditional:
b = [True for num in a if num > 3]
However, this only returns true values for elements that are above 3, so we get:
[True, True, True]
I know we can use multi-line approaches for this, but is there a way to just expand the conditional statement here to keep it on one line in this form, and return False if the condition is not met? In the end, I'd like this to return the following for "a" above:
[False, False, False, True, True, True]
Just move the condition from the filter to the expression
>>> a = [1, 2, 3, 4, 5, 6]
>>> [n > 3 for n in a]
[False, False, False, True, True, True]
Use a ternary operator:
b = [True if num > 3 else False for num in a]
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