Split a list based on a condition 1

Split a list based on a condition

good, bad = [], []
for x in mylist:
    (bad, good)[x in goodvals].append(x)
    
# good.append(x) if x in goodvals else bad.append(x)
# for x in mylist: (good if isgood(x) else bad).append(x)
# (good if x in goodvals else bad).append(x)

Here is what the above code is Doing:
1. The expression (bad, good)[x in goodvals] is a tuple containing the two lists, bad and good.
2. The expression x in goodvals is a boolean that’s True if x is in goodvals and False otherwise.
3. The boolean value is used to index the tuple, so that if x is in goodvals, the expression evaluates to good, and if x is not in goodvals, the expression evaluates to bad.
4. The append method is called on the list that was selected.

Similar Posts