3 ms·
lambdas can be really nice for use with python's more functional builtins, like filter, map, and sort. As an example, suppose you have a list like this: x =
by tsuraan 15y ago
lambdas can be really nice for use with python's more functional builtins, like filter, map, and sort. As an example, suppose you have a list like this:
x = [{1: 'b', 2: 'a'}, {1:'a', 2:'b'}]
You want to sort it on the value at the "2" key. You could write a dummy function:
def extract_2(dct):
return dct[2]
x.sort(key=extract_2)
Or, you could just use a quick lambda:
x.sort(key=lambda dct: dct[2])
The latter is more terse, and to a functional programmer, more clear (YMMV, of course). Lambda is just syntactic sugar in python; it's not necessary, and a lot of places where a functional programmer uses it in python make more sense as list comprehensions, but I think it's a nice thing to have.
EDIT:
I think the biggest reason I prefer the lambda approach to the named-function approach is that I don't like seeing one-off functions defined first and then seeing them used later. If python could do this:
x.sort(key=extract_2)
def extract_2(dct):
return dct[2]
or even somehow support ruby-style blocks, it wouldn't be so ugly to my eye. Python lets functions call functions that are defined below them at the module level, but not at the function level, so the above isn't valid in the scope of a function.