| Tip 60 | Savvy Anonymous Functions |
★★★2.7, 3.4+ In Python, you can have statements that do nothing (Tip 18, Pass It) and variables never that get used (Tip 10, Mark Dummy Variables). You can also have throw-away functions without names. They are known as anonymous functions or lambda functions.
A lambda function is a one-liner: a function that essentially consists of one statement. The value of the statement is the value returned by the function. If you need more than one statement, a lambda function is not going to help.
A lambda function does not have a name. You create it as needed with the lambda keyword, use it at once, and discard it. Here is a lambda function that squares its parameter:
| | z = (lambda x: x * x)(3) |
| => | 9 |
And this ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access