Lesson guide
What this Python exercise practices
Partition a list by a condition is a intermediate practice lesson that focuses on lists, iteration, filtering. It is designed to be solved in about 18 minutes with examples, starter code, and test feedback.
Prerequisites
- Python variables
- List values
- Basic indexing
Difficulty and time
- Level
- Intermediate
- Estimated time
- 18 minutes
Practice path
Summary
Split a list into two lists based on a predicate function.
Problem statement
Implement partition(lst, predicate) which takes a list and a predicate (a function that returns True or False for an element). Return a tuple of two lists: (true_list, false_list). true_list contains elements for which predicate(element) is True, in their original order; false_list contains the rest, also preserving order. The function should work for any callable predicate.
Task
Practice using higher-order functions and list construction to separate elements that match a condition from those that don't.
Examples
Partition evens and odds
Input
partition([1, 2, 3, 4, 5], lambda x: x % 2 == 0)
Output
([2, 4], [1, 3, 5])
Explanation
Even numbers go to the first list, odd numbers to the second, preserving order.
Input format
Two arguments: a list and a predicate function (e.g., lambda x: x>0).
Output format
A tuple of two lists: (elements_where_predicate_true, elements_where_predicate_false).
Constraints
Do not modify the input list in-place. Preserve the relative order of elements in both output lists.
Samples
Sample input 0
partition([0, -1, 2], lambda x: x >= 0)
Sample output 0
([0, 2], [-1])
Explanation 0
0 and 2 satisfy the predicate, -1 does not.
AI assistant
Ask me anything!
Need help? I can explain the core idea behind this problem, review your current code, and give targeted hints. Use “Teach Theory” for the concept, “Get AI hint” for a quick scaffold nudge, or ask a specific question below.
Chat history is temporary and will not be saved.
Free preview includes 1 Teach Theory response and 1 AI hint per unlocked preview lesson.