Reputation: 420
I have one list containing True and False values. Using list comprehension, out of this list, I can get two separate lists where one has only True values and the other one has only False values as under:
aList = [True, False, False, True, False, True, True]
trues = [ x for x in aList if x==True ]
falses = [ x for x in aList if x==False ]
print(trues) # [True, True, True, True]
print(falses) # [False, False, False]
Is it possible to get two separate lists out of one list using list comprehension in one line? Something like:
trues, falses = [ [a,b] for x in aList a=True if x else b=False]
Here, I get the error: "SyntaxError: invalid syntax" mentioning caret just below 'True' of a=True
Upvotes: 1
Views: 1048
Reputation: 1598
It's more or less the same that you have but compressed in one line:
aList = [True, False, False, True, False, True, True]
trues,falses = [x for x in aList if x], [x for x in aList if not x]
This way you'll get two lists. If you enclose it in brackets, you'll get one list.
Upvotes: 1