Scope, Lambda & Higher-Order Functions
Lesson 3 of 6 · View course roadmap
Learn the idea
Scope: variables created inside a function are local — they vanish when it returns. Functions can read outer variables but assignment creates a new local one (unless you use global, which you should avoid).
Lambdas are tiny anonymous functions: lambda x: x * 2. Their killer use is as sort keys:
sorted(words, key=len)— sort by lengthsorted(users, key=lambda u: u["age"])— sort dicts by a fieldmax(nums, key=abs)— max by absolute value
Functions are values in Python — you can pass them around like any other object. That idea powers decorators, callbacks and most frameworks.
Where you'll use this
key= functions drive real product features: 'sort products by price', 'newest first', 'closest to you' — each is one lambda. Callbacks in GUIs and web frameworks are this same functions-as-values idea.
Common mistakes
- Assigning to an outer variable inside a function creates a new local one instead — the outer stays unchanged (use return values, not
global). - Multi-line logic crammed into a lambda — if it doesn't fit on one line, def a named function.
- sorted() vs .sort() again: sorted returns the new list; .sort() mutates and returns None.
Pro tip
min/max/sorted all share key=, and the operator module replaces common lambdas: sorted(users, key=itemgetter('age')) reads better and runs faster than the lambda version.
Try it yourself
The lesson example is loaded and ready — press Run, then change something and run it again. Breaking it is part of learning. Want a clean slate? Tap “New blank”.
Output appears here…
Pass the challenge +30 XP
Sort the starter list of (name, score) tuples by score from highest to lowest and print each name on its own line.
Kai Ash Rio
sorted(players, key=lambda p: p[1], reverse=True)
players = [("Rio", 12), ("Kai", 31), ("Ash", 22)]
for name, score in sorted(players, key=lambda p: p[1], reverse=True):
print(name)
Run your code to check it…
Check your understanding
Your notes (saved on this device)
Tip: use ← and → to move between lessons, ⌘K to search everything.