← Practice
πŸ“– Higher-order functionsLearning path
Browsing as guestΒ·Sign in or create a free account to save progress and use tutor tools.
LessonΒ·difficulty 2/5Β·~12 min

Higher-order: filter then map

A higher-order function takes another function as an argument. Two classics are filter (keep items that pass a test) and map (transform every item):

python
nums = [1, 5, 8, 9]
filter(lambda n: n % 2 == 0, nums)   # keeps the evens: 8
map(lambda n: n + 1, nums)           # adds one to each item
list(...)                            # both are lazy β€” wrap in list() to see values

Chaining them is a clean pipeline: first filter the data, then map a transform over what survives.

Your task

Write positives_squared(nums) that keeps only the strictly positive numbers, then squares them, using filter() and map(). Return a list.

python
positives_squared([-2, -1, 0, 3, 4])   # [9, 16]
positives_squared([1, 2, 3])           # [1, 4, 9]
positives_squared([-5])                # []

Hint: first filter the list down to the strictly-positive numbers, then map a squaring lambda over what survives. Both are lazy, so wrap the final pipeline in list().

Tests

  • mixed signs
  • all positive
  • single negative
  • empty list

✦ Stuck? Ask for a spark

Sign in or create a free account to use your monthly AI explainer allowance.

warming up
Loading editor…
Consolewaiting

$ Console output will appear here.

>_AI coach
Sign in or create a free account to chat with the tutor.