Lambda functions
A lambda is a small function written in a single expression, without a name.
Python
square = lambda n: n * n
print(square(6))
add = lambda a, b: a + b
print(add(2, 3))lambda n: n * n means "a function that takes n and returns n * n". It is exactly the same as:
Python
def square(n):
return n * n
print(square(6))A lambda can only contain one expression, whose value is returned automatically. No statements, no loops, no return keyword.
Where lambdas shine: as arguments
Assigning a lambda to a name, as above, is legal but pointless; use def for named functions. Lambdas are for when a function needs to be passed somewhere briefly, especially as a key for sorting:
Python
words = ["banana", "Kiwi", "apple", "cherry"]
print(sorted(words)) # default: capitals first
print(sorted(words, key=lambda w: w.lower())) # ignore case
print(sorted(words, key=lambda w: len(w))) # by length
print(sorted(words, key=lambda w: w[-1])) # by last letterThe key function is called on each item, and the items are sorted by what it returns.
Sorting records
Python
students = [
{"name": "Asha", "grade": 92},
{"name": "Leo", "grade": 78},
{"name": "Mei", "grade": 85},
]
for s in sorted(students, key=lambda s: s["grade"], reverse=True):
print(s["name"], s["grade"])
best = max(students, key=lambda s: s["grade"])
print("Best:", best["name"])max and min accept a key too.
Sorting by two things
Return a tuple from the key to sort by one value, then break ties with another:
Python
people = [("Mei", 24), ("Leo", 30), ("Asha", 24), ("Raj", 30)]
print(sorted(people, key=lambda p: (p[1], p[0]))) # by age, then name
print(sorted(people, key=lambda p: (-p[1], p[0]))) # oldest first, then nameFinished this lesson?Mark it complete to earn +20 XP and move your progress on.