Lambda
A small anonymous function written in one line with the lambda keyword.
A lambda is a tiny function with no name, written inline: lambda x: x * 2. It lists its arguments before the colon and returns the single expression after it — no def or return needed.
Lambdas shine as a quick argument to functions like sorted(), map(), or filter() when a full named function would be overkill. For anything longer, use def.
double = lambda x: x * 2
print(double(5))
pairs = [("a", 3), ("b", 1), ("c", 2)]
pairs.sort(key=lambda pair: pair[1]) # sort by the number
print(pairs)
Output
10
[('b', 1), ('c', 2), ('a', 3)]
Where this shows up in real Python
Lambdas shine as short, throwaway functions passed to other functions — most often the key= for sorting or finding a max.
Commonly used Lambda tools
lambda x: x * 2— an inline, unnamed functionsorted(items, key=lambda r: r['age'])— sort by a computed keymax(items, key=lambda x: len(x))— pick by a computed value
Official documentation: Python Tutorial: Lambda Expressions