Why would you want an anonymous function? Let's try sorting a list of dictionaries:
data = [{'Name':'Albert', 'age':32}, {'Name':'Yuen', 'age':16}, {'Name':'Priya', 'age':45}] print(sorted(data)) print(sorted(data, key=lambda item : item['age']))
The results should look like this:
We defined a list of dictionaries, each of which contains data about a person. We then used the sorted
function to sort the items in the list. The first time we called sorted
, it appeared that the list had been sorted alphabetically, by the first letter of each name. This behaviour is unpredictable—if we added a last name to each dictionary, would the first or last name be used as the sorting key? To prevent this kind of problem, we can use the keyword key
to specify a function that is called on each item before sorting takes place. In the second function call, we used lambda
to define an anonymous function that returns the...