Free lab Real Python 3. Zero installs. Your code stays in this browser. Open the playground

Scope, Lambda & Higher-Order Functions

14 min 30 XP
Study loop Read Predict Run Tweak Prove Review
Lesson 3 of 6 · View course roadmap
Step 1

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 length
  • sorted(users, key=lambda u: u["age"]) — sort dicts by a field
  • max(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.

Step 2

Try it yourself

Blank · autosaved

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”.

PYexample.py
+ Enter to run
Output appears here…
Step 3

Pass the challenge +30 XP

Blank · autosaved

Sort the starter list of (name, score) tuples by score from highest to lowest and print each name on its own line.

Target output
Kai
Ash
Rio
PYchallenge.py
Run your code to check it…
Step 4

Check your understanding

1. What is lambda x: x + 1?
2. sorted(names, key=len) sorts by…
Last step

Your notes (saved on this device)

Tip: use and to move between lessons, K to search everything.

Your next ten minutes

Write Python that does something useful.

Start free. No install, no card, no passive video marathon.

Start learning free → Explore the path