A lambda function is a small, nameless function written on a single line. It is mostly used to pass it to another function, such as sorted, max or min.
A lambda function
These two definitions do exactly the same:
def double(x):
return x * 2
double2 = lambda x: x * 2
print(double(4)) # 8
print(double2(4)) # 8
The syntax is lambda parameters: expression. The result of the expression is what the function returns; you do not write return.
add = lambda a, b: a + b
print(add(2, 3)) # 5
greeting = lambda: "hello"
print(greeting()) # hello
A lambda can only contain one expression: it does not allow several lines or loops. If the logic is longer, write a normal function with def.
sorted with key
By default sorted sorts the elements as they are. The key parameter receives a function that calculates the value by which each element is sorted:
words = ["star", "sun", "sea", "moon"]
print(sorted(words)) # ['moon', 'sea', 'star', 'sun'] (alphabetical)
print(sorted(words, key=len)) # ['sun', 'sea', 'star', 'moon'] (by length)
print(sorted(words, reverse=True)) # ['sun', 'star', 'sea', 'moon']
With a lambda you can sort by any criterion, for example the last letter:
print(sorted(words, key=lambda w: w[-1]))
# ['sea', 'sun', 'moon', 'star']
Sorting is stable
If two elements have the same key, they keep the order they had. That is why in the previous example sun goes before sea when sorted by length, just like in the original list.
Sorting lists of tuples or dictionaries
students = [("ana", 8), ("luis", 6), ("eva", 9)]
by_grade = sorted(students, key=lambda s: s[1], reverse=True)
print(by_grade) # [('eva', 9), ('ana', 8), ('luis', 6)]
records = [{"name": "ana", "age": 30}, {"name": "luis", "age": 25}]
print(sorted(records, key=lambda r: r["age"]))
# [{'name': 'luis', 'age': 25}, {'name': 'ana', 'age': 30}]
Sorting a dictionary by value
grades = {"ana": 8, "luis": 6, "eva": 9}
ranking = sorted(grades.items(), key=lambda pair: pair[1], reverse=True)
print(ranking) # [('eva', 9), ('ana', 8), ('luis', 6)]
max and min with key
max and min also accept key. If there is a tie, they return the first one:
students = [("ana", 8), ("luis", 9), ("eva", 9)]
print(max(students, key=lambda s: s[1])) # ('luis', 9)
print(min(students, key=lambda s: s[1])) # ('ana', 8)
print(max(["sun", "star", "sea"], key=len)) # star
Practice in Sorting with key and The best student.