A lambda function is a small, anonymous function in Python, created using the lambda keyword. It's ideal for quick, one-time operations without needing a full def function.
🔧 Syntax:
lambda arguments: expressionTakes any number of arguments, but only one expression.
Automatically returns the value of the expression.
💡 Example: Square a Number
square = lambda x: x * x
print(square(5)) # Output: 25🔄 Use in map(), filter(), and sorted()
nums = [1, 2, 3, 4]
# Squaring each number
squares = list(map(lambda x: x**2, nums))
print(squares) # [1, 4, 9, 16]🔍 More Examples:
Filter even numbers:
evens = list(filter(lambda x: x % 2 == 0, nums))
print(evens) # [2, 4]Sort list of tuples by second item:
pairs = [(1, 3), (2, 1), (4, 2)]
sorted_pairs = sorted(pairs, key=lambda x: x[1])
print(sorted_pairs) # [(2, 1), (4, 2), (1, 3)]💡 Real-Life Analogy:
Think of a lambda like a sticky note with a quick formula — small, disposable, and used instantly when needed.