Python Docs
Python Lambda — Full Notes
A lambda function is a small, anonymous function in Python. It can take any number of arguments but contains only one expression.
What is a Lambda Function?
Lambda functions are used when you need a short, throwaway function.
Lambda Syntax
lambda arguments : expressionThe expression is evaluated and returned automatically.
Basic Lambda Examples
Add 10 to a number
x = lambda a : a + 10
print(x(5))Multiply two numbers
x = lambda a, b : a * b
print(x(5, 6))Sum three numbers
x = lambda a, b, c : a + b + c
print(x(5, 6, 2))Why Use Lambda Functions?
Lambda functions are extremely useful with closures and function factories.
Function returning a lambda
def myfunc(n):
return lambda a : a * n
mydoubler = myfunc(2)
print(mydoubler(11))Triple any number
def myfunc(n):
return lambda a : a * n
mytripler = myfunc(3)
print(mytripler(11))Doubler + Tripler together
def myfunc(n):
return lambda a : a * n
mydoubler = myfunc(2)
mytripler = myfunc(3)
print(mytripler(11))Lambda with Built-in Functions
Lambda works perfectly with map(), filter(), and sorted().
Using lambda with map()
numbers = [1, 2, 3, 4, 5]
doubled = list(map(lambda x: x * 2, numbers))
print(doubled)Using lambda with filter()
numbers = [1, 2, 3, 4, 5, 6, 7, 8]
odd_numbers = list(filter(lambda x: x % 2 != 0, numbers))
print(odd_numbers)Using lambda with sorted()
students = [("Emil", 25), ("Tobias", 22), ("Linus", 28)]
sorted_students = sorted(students, key=lambda x: x[1])
print(sorted_students)Sort strings by length
words = ["apple", "pie", "banana", "cherry"]
sorted_words = sorted(words, key=lambda x: len(x))
print(sorted_words)When to Use Lambda?
Use lambda when you need a small, quick function inside map(), filter(), sorted(), or as a return value from functions.