How to split a list by condition in Python

Splits a list into two lists based on a condition function, returning matched and unmatched items.

Easy Python 3.9+ Aug 9, 2026 Lists & loops 11 views 0 copies

Python code

21 lines
Python 3.9+
def split_by_condition(items, condition):
    """
    Split a list into two lists based on a condition.
    The first list contains items where condition(item) is True,
    the second list contains the rest.
    """
    matched = []
    unmatched = []
    for item in items:
        if condition(item):
            matched.append(item)
        else:
            unmatched.append(item)
    return matched, unmatched


if __name__ == "__main__":
    numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
    evens, odds = split_by_condition(numbers, lambda n: n % 2 == 0)
    print("Even numbers:", evens)
    print("Odd numbers:", odds)

Output

stdout
Even numbers: [2, 4, 6, 8, 10]
Odd numbers: [1, 3, 5, 7, 9]

How it works

The split_by_condition function iterates over each item, evaluates the condition, and appends to one of two lists. This is O(n) — it scans the input once. Splitting into separate lists is useful for partitioning data without altering the original order. The function returns both lists as a tuple, allowing easy unpacking.

Common mistakes

  • Modifying the list while iterating over it, causing skipped items.
  • Forgetting that the condition must return a boolean, not a value like None.
  • Assuming the original list order is preserved in both output lists.

Variations

  1. Use a list comprehension and a set for large lists: `matched = [x for x in items if condition(x)]` and `unmatched = [x for x in items if not condition(x)]`.
  2. Use `itertools.filterfalse` for a functional-style split.

Real-world use cases

  • Partitioning a list of user events into valid and invalid records before saving to a database.
  • Filtering logs into error and non-error entries for separate processing pipelines.
  • Splitting sensor readings into normal and outlier values for real-time alerting.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Lists & loops

Related tutorials and quizzes for this topic.