Browser lab15 min+60 XP

Lambda functions

A whole function in one line, perfect for sorting by any rule you like.

0% done

Code runs right here in your browser. Nothing to install.

TASK 1

Learn it

Key idea

A lambda is a one-line function, perfect as a sorting key.

Key words
def double(x):    return x * 2double = lambda x: x * 2("Nova", 128)("Kai", 95)("Mira", 140)key=lambda p: p[1]("Kai", 95)("Nova", 128)("Mira", 140)same jobsorted
A lambda does the same job as a small def, and makes a great sorting key.

A lambda is a tiny function with no name, written in one line: lambda x: x * 2. The part before the colon is the parameter, and the part after it is the value it returns. No def and no return needed.

Lambdas shine as a key function: a rule that tells sorted(), max() or min() what to compare. sorted(players, key=lambda p: p[1]) sorts players by their second item, the score.

Keep lambdas short. If the rule needs more than one simple expression, write a normal function with def instead. It is easier to read and test.

Real life linkWhen you tap "sort by price" in a shopping app, the app is handed a tiny rule: use the price. A lambda is a tiny rule like that.
Example code
double = lambda x: x * 2
print(double(5))
players = [("Nova", 128), ("Kai", 95), ("Mira", 140)]
print(sorted(players, key=lambda p: p[1]))
print(max(players, key=lambda p: p[1]))
TASK 2

Try it yourself

+10 XP

Sort the words list by their last letter using a lambda key. It should print ['torch', 'map', 'vault', 'key'].

Create a free account to start this lab

Sign in to write, run and check your code here. Your progress, XP and code are saved to your account. No card needed.

TASK 3

Capture the flag

+10 XP

What does (lambda n: n + 1)(4) give?

Create a free account to start this lab

Sign in to answer the flag question. Your progress, XP and code are saved to your account. No card needed.

HOMEWORK

Lambda leaderboard

+20 XP

Sort the players list of dictionaries by score, highest first, using a lambda. Print a numbered leaderboard like 1. Mira 140, then use min() with a lambda to print Shortest name: Kai.

Create a free account to start this lab

Sign in to do this homework and have it checked. Your progress, XP and code are saved to your account. No card needed.