Python Lambda Expressions
lambda is a fancy way to define a small anonymous function inline. You never have to use
lambda expressions, but they can make your code more concise in certain situations, such as providing callback functions.
Consider a simple function that adds to inputs together. We could write it the traditional way via a named function
>>> def add(x, y): ... return x + y ... >>> add(3,4) 7
We can also write it as a one-line
lambda expression as follows:
>>> add = lambda x, y: x + y >>> add(3,4) 7
lambda expressions only work for single expressions where the result is a return value. You cannot use them with multiple statements, iterations, conditions, error handling, etc.
lambda expressions have an interesting history. At one time the plan was for them to be removed entirely from Python 3, but after much debate Guido van Rossum, the BDFL of Python, decided to just keep them.
Want to improve your Python? I have a list of recommended Python books.