April 2016
Intermediate to advanced
486 pages
9h 21m
English
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 the sort key for the sorted function:
>>> class Spam(object): ... def __init__(self, value): ... self.value = value ... ... def __repr__(self): ... return '<%s: %s>' % (self.__class__.__name__, self.value) ... >>> spams = [Spam(5), Spam(2), Spam(4), Spam(1)] >>> sorted_spams = sorted(spams, key=lambda spam: spam.value) >>> spams [<Spam: 5>, <Spam: 2>, <Spam: 4>, <Spam: 1>] >>> sorted_spams [<Spam: 1>, <Spam: 2>, <Spam: 4>, <Spam: ...