0
0
PythonHow-ToBeginner · 3 min read

How to Partition List Based on Condition in Python

To partition a list based on a condition in Python, use list comprehensions to create two lists: one with elements that meet the condition and one with those that don't. Alternatively, use itertools.filterfalse for a clean approach to separate elements.
📐

Syntax

You can partition a list by using two list comprehensions: one for elements that satisfy the condition and one for those that don't.

Syntax:

list_true = [x for x in original_list if condition(x)]
list_false = [x for x in original_list if not condition(x)]

Here, condition(x) is a function or expression that returns True or False for each element x.

python
list_true = [x for x in original_list if condition(x)]
list_false = [x for x in original_list if not condition(x)]
💻

Example

This example partitions a list of numbers into even and odd numbers using list comprehensions.

python
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
even_numbers = [n for n in numbers if n % 2 == 0]
odd_numbers = [n for n in numbers if n % 2 != 0]

print('Even numbers:', even_numbers)
print('Odd numbers:', odd_numbers)
Output
Even numbers: [2, 4, 6, 8, 10] Odd numbers: [1, 3, 5, 7, 9]
⚠️

Common Pitfalls

A common mistake is to try to partition the list in one pass without storing results separately, which can lead to errors or inefficient code.

Also, using filter() alone only returns one filtered list, so you need two filters or comprehensions to get both parts.

python
numbers = [1, 2, 3, 4, 5]
# Wrong: trying to get both partitions in one filter call
# filtered = filter(lambda x: x % 2 == 0, numbers)

# Right: use two comprehensions
evens = [x for x in numbers if x % 2 == 0]
odds = [x for x in numbers if x % 2 != 0]
📊

Quick Reference

Use these tips to partition lists easily:

  • Use list comprehensions for clear and readable code.
  • Remember to create two lists: one for elements matching the condition, one for the rest.
  • For large lists, consider itertools.filterfalse to avoid scanning twice.

Key Takeaways

Partition a list by creating two lists with list comprehensions based on a condition.
Use condition(x) to decide which list each element belongs to.
Avoid trying to partition in one pass without separate storage for each group.
For large data, itertools.filterfalse can help separate elements efficiently.
List comprehensions provide a simple and readable way to split lists.