Think of a lambda function as a small function with no name.
It may take as many arguments as you like, but its body is limited to one expression.
Syntax
Python evaluates the expression and returns the result.
Example
Return argument a plus 10:
Output: complete Python program
x = lambda a : a + 10
print(x(5))
Example
Return the product of arguments a and b:
Output: complete Python program
x = lambda a, b : a * b
print(x(5, 6))
Example
Return the sum of arguments a, b and c:
Output: complete Python program
x = lambda a, b, c : a + b + c
print(x(5, 6, 2))
lambda arguments : expression
Why Use Lambda Functions?
Lambdas are at their best when used as an anonymous function inside another function.
Picture a function with one parameter, where the lambda it returns multiplies a number you haven't supplied yet by that parameter.
Example
Output: complete Python program
def myfunc(n):
return lambda a : a * n
mydoubler = myfunc(2)
print(mydoubler(11))
Example
Output: complete Python program
def myfunc(n):
return lambda a : a * n
mytripler = myfunc(3)
print(mytripler(11))
Example
Output: complete Python program
def myfunc(n):
return lambda a : a * n
mydoubler = myfunc(2)
mytripler = myfunc(3)
print(mydoubler(11))
print(mytripler(11))
Lambda with Built-in Functions
You will often see lambda functions passed to built-ins such as map(), filter() and sorted().
Example
Multiply every number in a list by two:
Output: complete Python program
numbers = [1, 2, 3, 4, 5]
doubled = list(map(lambda x: x * 2, numbers))
print(doubled)
Example
Keep only the odd numbers from a list:
Output: complete Python program
numbers = [1, 2, 3, 4, 5, 6, 7, 8]
odd_numbers = list(filter(lambda x: x % 2 != 0, numbers))
print(odd_numbers)
Example
Order a list of tuples by their second element:
Output: complete Python program
students = [("Emil", 25), ("Tobias", 22), ("Linus", 28)]
sorted_students = sorted(students, key=lambda x: x[1])
print(sorted_students)
Example
Order strings from shortest to longest:
Output: complete Python program
words = ["apple", "pie", "banana", "cherry"]
sorted_words = sorted(words, key=lambda x: len(x))
print(sorted_words)