lambda functions
The lambda
statement in Python is simply an anonymous function. Due to the syntax, it is slightly more limited than regular functions, but a lot can be done through it. As always though, readability counts, so generally it is a good idea to keep it as simple as possible. One of the more common use cases is as the sort
key for the sorted
function:
>>> import operator
>>> values = dict(one=1, two=2, three=3)
>>> sorted(values.items())
[('one', 1), ('three', 3), ('two', 2)]
>>> sorted(values.items(), key=lambda item: item[1])
[('one', 1), ('two', 2), ('three', 3)]
>>> get_value = operator.itemgetter(1)
>>> sorted(values.items(), key=get_value)
[('one', 1), ('two', 2), ('three', 3)]
The first version sorts by key and the second sorts by the value. The last one shows an alternative option using operator.itemgetter
...