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.
Python code
21 linesdef 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
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
- 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)]`.
- 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
More from Lists & loops
- Check if List is Sorted Ascending in Python easy
- Compare Two Lists in Python: Common, Only in First, Only in Second easy
- Convert a List of Integers to a Comma-Separated String in Python easy
- Enumerate a Python List with a Custom Start Index easy
- Extract Data by Type from a List in Python: Numbers and Strings easy
- Find All Occurrences of an Item in a Python List easy
Keep learning
Related tutorials and quizzes for this topic.