Lesson guide
What this Python exercise practices
Filter a list using a predicate is a intermediate practice lesson that focuses on lists, iteration, filtering. It is designed to be solved in about 13 minutes with examples, starter code, and test feedback.
Prerequisites
- Python variables
- List values
- Basic indexing
Difficulty and time
- Level
- Intermediate
- Estimated time
- 13 minutes
Practice path
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'.
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.