Module 07 · Lesson 01
Lambda Functions and Higher-Order Builtins
Pass functions as values: write small lambdas and use them with sorted, min, max, map and filter, then pair data with zip and test it with any and all.
- About 8 minutes
- Builds on earlier lessons
- 12-question quiz at the end
What you will learn
- Functions as values
- Sort with key=
- map, filter and zip
- Watch a leaderboard sort
Functions you can pass around
A function is a value, like a number or a list. You can store it, hand it to another function and call it later.
lambda
lambda n: n * 2is a tiny function with no name and one expression.key=
sorted(),min()andmax()take akeyfunction that says what to compare.map and filter
map()changes every item.filter()keeps only the items that pass a test.zip, any, all
zip()pairs lists up.any()andall()answer yes or no about a whole list.
Passing functions everywhere
Whenever an app sorts, filters or picks the best of something, a small function is usually doing the choosing.
- PlaylistsSort songs by length or by plays with one
key=function. - Leaderboards
max(players, key=...)finds the top scorer in one line. - Online shopsSort by price, keep only your size, and pair names with prices using
zip(). - Form checks
all()makes sure every field is filled in before you press Send.
Sorting with a key
This line sorts players by their score. Tap each part to see its job.
Part 1 of 7
result:sorted() hands back a new list, stored under this name.
Pass functions around
Pick an example, change it, then press Run. Say what you expect to see before you press.
Example 1 of 6A lambda
A lambda is a function in one line. Store it under a name and call it like any function.
Your turn: Write a lambda half that divides a number by 2, then print half(9).
double = lambda n: n * 2
shout = lambda word: word.upper() + "!"
print(double(21))
print(shout("hello"))Press Run to see what it prints.Watch a leaderboard sort
Press Step to run one line at a time. Watch the names box change.
Ready. Press Step to run the first line.
- players = [("Ana", 82), ("Ben", 95), ("Cy", 77)]
- by_score = lambda p: p[1]
- ranked = sorted(players, key=by_score, reverse=True)
- best = ranked[0]
- names = list(map(lambda p: p[0], ranked))
- print(best[0], "wins with", best[1])
- print(names)
Output so far
Nothing printed yet.
What Python does
Python reads the program from the top. Nothing has run yet.
Names
None yet.
Quick guesses
Guess first, then read why. A wrong guess is where the learning happens. Nothing here is scored.
Question 1 of 6
1.Numbers written as text: what prints?
print(sorted(["10", "9", "100"]))0 of 6 answered
Common lambda misconceptions
Each card is something learners often believe. Tap it to see what Python really does.
Misconception 1 of 4
Notes
Everything above, in words. Open it when you want the full explanation.
Read the notesNotesOpenClose
Syntax
The general shape of the statements in this lesson.
lambda x: x * 2 # one-expression function lambda a, b: a + b # several parameters sorted(items, key=len) # pass a function, do not call it sorted(items, key=lambda x: x[1], reverse=True) max(items, key=lambda x: x["score"]) list(map(func, items)) # apply func to every item list(filter(func, items)) # keep items where func is true zip(names, ages) # pairs, stops at the shortest any(items) / all(items)
Press Run to see what it prints.Worked examples
Read the problem, run the code, then read why it works.
Example 1 of 2
Ranking a leaderboard
A list of (player, points) tuples arrives unsorted. Print the players from highest to lowest points, with their rank, and name the player with the fewest points.
players = [("Mia", 340), ("Leo", 515), ("Zoe", 290), ("Raj", 515)]
ranked = sorted(players, key=lambda p: p[1], reverse=True)
for rank, (name, points) in enumerate(ranked, start=1):
print(f"{rank}. {name} {points}")
last = min(players, key=lambda p: p[1])
print("Needs practice:", last[0])Press Run to see what it prints.Predict first
How it works(open after your guess)
Common pitfalls
Mistakes people make with this topic, and what to write instead.
Pitfall 1 of 3
Calling the key function instead of passing it
Spot the bug
Can you see what is wrong? Run it to watch it go wrong, then open the fix.
words = ["pear", "fig"] print(sorted(words, key=len()))
Press Run to see what it prints.Show what goes wrong and the fixWhat goes wrong and the fix
In the real world
Where this shows up in software people use every day.
- Online retail
Sorting products for a shop page
A small online shop lets visitors sort products by price or by rating. The same product list is sorted with a different key depending on the button pressed.
Why Python fits
Each button only changes the key, so one product list serves every view.
filterbuilds the budget view without touching the original list.Pythonproducts = [ {"name": "Lamp", "price": 35.0, "rating": 4.2}, {"name": "Mug", "price": 8.5, "rating": 4.8}, {"name": "Rug", "price": 120.0, "rating": 3.9}, ] by_price = sorted(products, key=lambda p: p["price"]) print([p["name"] for p in by_price]) top = max(products, key=lambda p: p["rating"]) print("Best rated:", top["name"]) in_budget = list(filter(lambda p: p["price"] <= 40, products)) print(len(in_budget), "items under 40")OutputPress Run to see what it prints.
Key takeaways
Tick each one you could explain to a friend.
0 of 5
Common questions
Guess the answer first, then open it.
Is a lambda faster than a def?
Can a lambda contain an if?
How do I sort by two things?
Does sorted change my original list?
Your notes
Sign in to keep private notes alongside this lesson.
Where to go next
The quiz and the Lab live on their own pages, so this lesson stays about learning.
Finished this lesson?
Create an ID or sign in to save your progress across devices.
Check what you learned
12 questions, with an explanation after every answer. A verified attempt counts towards opening the module Lab.
Keep going in the Lab
7 tasks on this lesson, from writing code to tracing it by hand. Practice only, no XP.
Spaced review
Questions you miss in a quiz come back on a spaced schedule, so what you learned here sticks.
This lesson at a glance
The 9 lines of code this lesson uses, each with a short note. Keep it open while you do the quiz and the Lab.
What else you can search for and explore
Curious to go further? Each card opens a web search in a new tab.
References
Look things up here whenever you need the exact details.