Menu

Sign in to track your progress and unlock all features.

Theme style

Log in

Full lesson preview

Filter and transform using comprehension

Filter a list with a predicate and transform each passing element with a mapping function using a comprehension.

Python practice17 minList & Dictionary PatternsIntermediateLast updated March 20, 2026

Problem statement

Create a function that takes a list of items, a predicate function, and a transform function. Return a new list containing transform(x) for each x in items where predicate(x) is truthy. Use a list comprehension in the implementation. The predicate and transform must be callable; raise TypeError if they are not. This pattern is a common combination of filter + map and is succinctly expressed with a single comprehension.

Task

Practice writing concise, readable list comprehensions that combine filtering and mapping.

Examples

Square even numbers

Input

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

Output

[4, 16]

Keeps even numbers and squares them.

Input format

A list of items, a predicate callable, and a transform callable: (items, predicate, transform)

Output format

A list of transformed items where each original item satisfied the predicate.

Constraints

- predicate and transform must be callable; raise TypeError otherwise. - Do not use external libraries. - Preserve order of the original list for elements that pass the predicate.

Samples

Sample 1

Input

filter_transform(['a','abcd','abcde'], lambda s: len(s)>3, lambda s: s.upper())

Output

['ABCD', 'ABCDE']

Filter strings longer than 3 and convert to uppercase.