Lambdas
Lambdas
One line anonimous functions.
You might want to use lambdas when you don’t want to use a function twice in a program.
They are just like normal functions and even behave like them.
Blueprint
lambda argument: manipulate(argument)
Example
add = lambda x, y: x + y
print(add(3, 5))
# Output: 8
Use cases
List sorting
a = [(1, 2), (4, 1), (9, 10), (13, -3)]
a.sort(key=lambda x: x[1])
print(a)
# Output: [(13, -3), (4, 1), (1, 2), (9, 10)]
Parallel sorting of lists
data = zip(list1, list2)
list1, list2 = map(lambda t: list(t), zip(*data))
Last updated