Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

arrays

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]
like image 813
Topher Avatar asked Dec 02 '22 14:12

Topher


2 Answers

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]
like image 101
Abhijit Avatar answered Dec 06 '22 09:12

Abhijit


Use a ternary operator:

b = [True if num > 3 else False for num in a]
like image 29
TigerhawkT3 Avatar answered Dec 06 '22 09:12

TigerhawkT3