Menu

Sign in to track your progress and unlock all features.

Theme style

Log in

Problem No 17

Partition a list by a condition

Medium

18 minute session

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.

Code editor
Loading editor…

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.

10:49 PM

Free preview includes 1 Teach Theory response and 1 AI hint per unlocked preview lesson.