Python Lambda Examples — Code + Output
This PDF shows several practical examples of Python lambda (anonymous) functions, their code, and the
actual output produced when run. Each example includes a short description, the lambda code, and the
result of execution.
Simple Add Lambda
add = lambda x, y: x + y
print(add(2, 3)) # Output: 5
Output: 5
Square Lambda
square = lambda x: x * x
print(square(6)) # Output: 36
Output: 36
Filter Even Numbers
nums = list(range(1, 11))
evens = list(filter(lambda x: x % 2 == 0, nums))
print(evens) # Output: [2,4,6,8,10]
Output: [2, 4, 6, 8, 10]
Map to Double
nums = list(range(1, 11))
doubles = list(map(lambda x: x*2, nums))
print(doubles) # Output: [2,4,...,20]
Output: [2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
Reduce to Sum
from functools import reduce
nums = list(range(1, 11))
s = reduce(lambda a,b: a+b, nums)
print(s) # Output: 55
Output: 55
Sort by Length using lambda
words = ['apple','banana','kiwi','strawberry','grape']
sorted_by_len = sorted(words, key=lambda w: len(w))
print(sorted_by_len) # Output: ['kiwi','grape','apple','banana','strawberry']
Output: ['kiwi', 'apple', 'grape', 'banana', 'strawberry']
Lambda as a Closure / Function Factory
def make_multiplier(n):
return lambda x: x * n
times3 = make_multiplier(3)
print(times3(5)) # Output: 15
Output: 15