Archived
lambdas
An old note — I haven't updated it since I wrote it.
Lambdas can often achieve the same work as a function, more concisely. Concise expressive code is good, because it enables you to do more, quicker.
Let's say we want to sort a list, but use the square of each entry to evaluate their position, rather than the value itself:
1A = [1, -4, 7, 5, 4, -3, 2]
2print(sorted(A, key=lambda x: x * x)
This is equivalent to:
1def pow2(x):
2 return x * x
3
4A = [1, -4, 7, 5, 4, -3, 2]
5print(sorted(A, key=pow2))
So the key differences are:
- lambdas are anonymous functions
- lambdas don't have a return statement
- lambdas are one liners
There are, in fact, more differences, but none we want to focus on right now.