──────────────────────────────────────

15. Festival Workshop Shortlist · Pass a Function as an Argument

Use a short lambda and a named function to filter and format records.

Lesson files · lessons/callables/function-callbacks

Before you start
- Filter records using a condition that gives True or False.
- Read values from a tuple and format them with an f-string.

By the end
- Filter activities by seat count and map the retained records to labels in input order.
- Explain what each callback receives and returns for an activity at the minimum.

Where you can use it
Filter activities by the seats a group needs, then format the matching records for the organiser’s sign-up sheet.

A callback is a function you pass to code that will call it. Pass a named function such as route_name without parentheses to give map the function itself. A lambda creates a function with one expression, whose value becomes the result. It can read max_minutes from the surrounding function. filter keeps each original item when its callback answers True. map transforms each remaining item. Both produce values as you ask for them, and list collects those values for printing.

Predict
What does filter give map for the Garden route?
- The pair ("Garden", 15).
- The value True.

Worked example (example.py)

def route_name(route):
    return route[0]


def nearby_names(routes, max_minutes):
    nearby = filter(lambda route: route[1] <= max_minutes, routes)
    return list(map(route_name, nearby))


routes = [("Pond", 12), ("Hill", 18), ("Garden", 15)]
print(nearby_names(routes, 15))


Example result
['Pond', 'Garden']

Use the starter festival activities. Read a minimum number of seats. In open_labels, filter the activities to those with at least that many seats, then use map with format_activity. Print the resulting list of labels in the original order.

Starter program (starter.py)

def format_activity(activity):
    name, seats = activity
    return f"{name} ({seats})"


def open_labels(activities, minimum):
    return list(map(format_activity, activities))


activities = [("Drums", 6), ("Clay", 0), ("Puppets", 4)]
print(open_labels(activities, int(input())))


Starter input
4

Hint
Pass filter a lambda that compares activity[1] with minimum. Map format_activity over the filtered records.

Case 1. Try the sample
Input
4
Expected output
['Drums (6)', 'Puppets (4)']

Case 2. Include zero seats
Input
0
Expected output
['Drums (6)', 'Clay (0)', 'Puppets (4)']

Case 3. No activity fits
Input
7
Expected output
[]

Stretch
Write the same filter and formatting as one list comprehension, then compare the results.

Reflect
Which callback decides what stays, and which one decides what gets printed?

Check your prediction
The pair ("Garden", 15). The lambda’s answer decides whether filter keeps the original pair.
