Lesson 31 of 4078%
(Progress persistence is disabled until Phase 9)
Python
Intermediate
Lambda Functions
Create small, anonymous functions.
Lambda Functions
What You’ll Learn
You’ll learn how to write small, anonymous, one-line functions using the lambda keyword.
What is a Lambda Function?
A lambda function can take any number of arguments, but can only have one expression.
Syntax:
lambda arguments : expression
# A regular function
def add_ten(a):
return a + 10
# The same function as a lambda
add_ten_lambda = lambda a : a + 10
print(add_ten(5)) # 15
print(add_ten_lambda(5)) # 15
Multiple Arguments
multiply = lambda a, b : a * b
print(multiply(5, 6)) # 30
Why use Lambda Functions?
The power of lambda is better shown when you use them as an anonymous function inside another function, like built-in sorting or mapping methods.
points = [(1, 2), (5, 1), (3, 8)]
# Sort by the second item in each tuple
points.sort(key=lambda x: x[1])
print(points) # [(5, 1), (1, 2), (3, 8)]