A one-line function that doesn't get a name. Useful when you need to pass a tiny function to another function.
# With def
def double(x):
return x * 2
# Same thing as a lambda
double = lambda x: x * 2
You'll mostly see lambdas inline, not stored in variables. The most common use: key= in sorted().
people = [
{"name": "Alice", "age": 30},
{"name": "Bob", "age": 25},
{"name": "Carol", "age": 35},
]
by_age = sorted(people, key=lambda p: p["age"])
# [{'name':'Bob',...}, {'name':'Alice',...}, {'name':'Carol',...}]
by_name_desc = sorted(people, key=lambda p: p["name"], reverse=True)
names = ["alice", "bob", "carol"]
upper = list(map(str.upper, names)) # ['ALICE', 'BOB', 'CAROL']
# Often clearer as a comprehension:
upper = [n.upper() for n in names]
ages = [12, 15, 18, 21, 17, 30]
adults = list(filter(lambda x: x >= 18, ages)) # [18, 21, 30]
# Also clearer as a comprehension:
adults = [x for x in ages if x >= 18]
map() / filter(). But you'll see all three in the wild — recognise them and you can read any Python code.
lambda x: expression — a tiny anonymous function.sorted(items, key=lambda i: i["something"]).Sort the people list above by age ascending, but use name as a tiebreaker. Hint: a lambda can return a tuple.