Skip to content
Advertisement

How can I partition (split up, divide) a list based on a condition?

I have some code like:

good = [x for x in mylist if x in goodvals]
bad = [x for x in mylist if x not in goodvals]

The goal is to split up the contents of mylist into two other lists, based on whether or not they meet a condition.

How can I do this more elegantly? Can I avoid doing two separate iterations over mylist? Can I improve performance by doing so?

Advertisement

Answer

good = [x for x in mylist if x in goodvals]
bad  = [x for x in mylist if x not in goodvals]

How can I do this more elegantly?

That code is already perfectly elegant.

There might be slight performance improvements using sets, but the difference is trivial. set based approaches will also discard duplicates and will not preserve the order of elements. I find the list comprehension far easier to read, too.

In fact, we could even more simply just use a for loop:

good, bad = [], []

for x in mylist:
    if x in goodvals:
        good.append(f)
    else:
        bad.append(f)

This approach makes it easier to add additional logic. For example, the code is easily modified to discard None values:

good, bad = [], []

for x in mylist:
    if x is None:
        continue
    if x in goodvals:
        good.append(f)
    else:
        bad.append(f)
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement