Creating Anonymous Functions with lambda
Published:
• Last updated:
• By Jeferson Peter
Python
Suppose you need a tiny function just once — writing a full
deffeels like overkill.
That’s when Python’slambdacomes in handy: quick, anonymous functions in one line.
Basic example
add = lambda x, y: x + y
print(add(2, 3))
# 5
With higher-order functions
nums = [1, 2, 3, 4]
squares = list(map(lambda x: x**2, nums))
print(squares)
# [1, 4, 9, 16]
As a key in sorting
words = ["apple", "banana", "kiwi"]
sorted_words = sorted(words, key=lambda w: len(w))
print(sorted_words)
# ['kiwi', 'apple', 'banana']
Conclusion
- Use
lambdafor small, inline functions. - Keep them simple — for more complex logic, use
def.