Lambda functions
A whole function in one line, perfect for sorting by any rule you like.
Code runs right here in your browser. Nothing to install.
Learn it
A lambda is a one-line function, perfect as a 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.
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]))
Try it yourself
+10 XPSort 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.
Capture the flag
+10 XPWhat 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.
Lambda leaderboard
+20 XPSort 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.