Anonymous Functions
The lambda keyword creates anonymous functions within Python expressions. However, Python’s simple syntax restricts the body of a lambda function to pure expressions. In other words, the body of a lambda function cannot contain assignments or use statements like while and try.
Anonymous functions are most suitable for use in parameter lists. For example, Example 5-7 rewrites the sorting of rhyming words from Example 5-4 using a lambda expression, thus eliminating the need for the reverse function.
Example 5-7 Sorting a list of words by reversing their spelling using a lambda expression
>>> fruits = ['strawberry', 'fig', 'apple', 'cherry', 'raspberry', 'banana']
>>> sorted(fruits, key=lambda word: word[::-1])
['banana', 'apple', 'fig', 'raspberry', 'strawberry', 'cherry']
>>>
Besides being passed as parameters to higher-order functions, anonymous functions are rarely used in Python. Due to syntactical limitations, non-trivial lambda expressions are either hard to read or impossible to write.
Refactoring Tips for lambda Expressions by Lundh If using a lambda expression makes a piece of code hard to understand, Fredrik Lundh suggests refactoring it as follows: (1) Write comments explaining the purpose of the lambda expression. (2) Spend some time studying the comments and find a name that summarizes them. (3) Convert the lambda expression into a def statement, using that name to define the function. (4) Remove the comments.
The lambda syntax is just syntactic sugar: like def statements, lambda expressions create function objects. This is one of several callable objects in Python. The next section will explain all callable objects.