Working with lambdas in python
23 Feb 2015Python provides a simple way to define anonymous functions through the use of the lambda
keyword. Today’s post will be a brief introduction to using lambdas in python along with some of the supported higher-order functions.
Declaration
For today’s useless example, I’m going to create a “greeter” function. This function will take in a name and give you back a greeting. This would be defined using a python function like so:
Invoking this function gives you endless greetings:
We can transform this function into a lambda with a simple re-structure:
Just to show you a more complex definition (i.e. one that uses more than one parameter), I’ve prepared a lambda that will execute the quadratic formula.
This is invoked just like any other function:
Higher order functions
Now that we’re able to define some anonymous functions, they really come into their own when used in conjunction with higher-order functions. The primary functions here are filter
, map
and reduce
.
We can filter a list of numbers to only include the even numbers.
Of course it’s the lambda x: x%2 == 0
performing the even-number test for us.
We can reduce a list of numbers to produce the accumulation of all of those values:
Finally, we can transform a list or map a function over a list of numbers and turn them into their inverses: