Menu

Sign in to track your progress and unlock all features.

Theme style

Log in

Problem No 13

Filter a list using a predicate

Medium

13 minute session

Summary

Return a new list containing only the elements that satisfy a given predicate function.

Problem statement

Given a list and a predicate (a callable that accepts a single argument and returns a truthy/falsy value), produce a new list containing only the elements for which the predicate returns a truthy value. Do not modify the original list. The predicate will be provided as a function or lambda. Preserve the original order of elements.

Task

Implement filter_list(lst, predicate) that returns a list of elements for which predicate(element) is truthy.

Examples

Filter even numbers

Input

filter_list([1, 2, 3, 4], lambda x: x % 2 == 0)

Output

[2, 4]

Explanation

The predicate keeps only numbers divisible by 2.

Input format

A list (lst) and a predicate function taking one argument.

Output format

A list containing elements from lst for which predicate(element) is truthy.

Constraints

Do not use external libraries. The predicate will be a callable. Maintain element order. Time complexity should be O(n).

Samples

Sample input 0

filter_list(['apple', 'banana', 'avocado'], lambda s: s.startswith('a'))

Sample output 0

['apple', 'avocado']

Explanation 0

Keeps only strings that start with 'a'.

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.

09:04 PM

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