Topher
Topher

Reputation: 498

Conditionals for evaluating True and False in a python list comprehension?

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]

Upvotes: 4

Views: 9419

Answers (2)

Abhijit
Abhijit

Reputation: 63717

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]

Upvotes: 17

TigerhawkT3
TigerhawkT3

Reputation: 49318

Use a ternary operator:

b = [True if num > 3 else False for num in a]

Upvotes: 5

Related Questions