Lambda is an anonymous (unnamed) function defined in one line.
Syntax:
1lambda arguments: expression
Examples:
1# Simple lambda2square = lambda x: x ** 23print(square(5)) # 2545# Multiple arguments6add = lambda a, b: a + b7print(add(2, 3)) # 589# With condition10max_value = lambda a, b: a if a > b else b
When to use:
sorted(), filter(), map().1# sorted with lambda2points = [(1, 2), (3, 1), (5, 4)]3sorted_points = sorted(points, key=lambda p: p[1])45# filter6evens = list(filter(lambda x: x % 2 == 0, range(10)))78# map9doubles = list(map(lambda x: x * 2, range(5)))
Don't use for complex logic — use def.