lambda in Python

What is lambda?

A lambda function in Python is an anonymous, inline function defined with the lambda keyword. It can have any number of arguments but only one expression. It's commonly used for short, simple functions.

Basic Syntax

lambda arguments: expression

Examples

# 1. Basic lambda function
square = lambda x: x * x
print(square(5))  # Output: 25
  
# 2. Lambda with multiple arguments
add = lambda x, y: x + y
print(add(3, 4))  # Output: 7
  
# 3. Using lambda with map
numbers = [1, 2, 3]
squares = map(lambda x: x ** 2, numbers)
print(list(squares))  # Output: [1, 4, 9]
  
# 4. Using lambda with filter
nums = [1, 2, 3, 4, 5]
even = filter(lambda x: x % 2 == 0, nums)
print(list(even))  # Output: [2, 4]
  
# 5. Using lambda with sorted
pairs = [(1, 'one'), (3, 'three'), (2, 'two')]
sorted_pairs = sorted(pairs, key=lambda x: x[1])
print(sorted_pairs)  # Output: [(3, 'three'), (2, 'two'), (1, 'one')]