Lesson 11 of 55
PythonLambda Functions
20 minutes
Course progress20%
What you'll learn
Keep these ideas in mind as you work through the lesson.
Lesson 11 of 55
Python20 minutes
Keep these ideas in mind as you work through the lesson.
Lambda (anonymous) functions are handy for short, throw‑away functionality. The syntax is lambda args: expression.
square = lambda x: x * x
print(square(5)) # 25
# Sorting a list of tuples by the second element
people = [(1, 'b'), (2, 'a'), (3, 'c')]
sorted_people = sorted(people, key=lambda item: item[1])
print(sorted_people)
Because a lambda can only contain a single expression, they’re best used as callbacks for functions like sorted, map, or filter.