Python treats functions as first class citizens. This provides a tonne of flexibility, but what exactly does it mean? Well, functions are basically instances of a type; just like the string ‘cat’ or the object ‘new_user’ created from the Customer class. With them we can:

Pass functions between methods

Compare them

Create private closures using functions within functions

And more…

The key part we want to focus upon is the first feature: Passing function between methods. This allows us to write code (methods or functions) that are not fully implemented but instead depend on the caller to supply the implementation.

PASSING FUNCTIONS BETWEEN METHODS

Here’s an example. The following method trims a sequence of numbers down to a smaller list and returns those numbers. But the method doesn’t decide which numbers matter. Rather the caller supplies a method to make that decision:

If we had a function like this that could determine whether a number was odd:

def check_for_odd(n):
return n % 2 == 1

Then we could combine that to get just the odd numbers:

find_special_numbers(check_for_odd, 25)

But writing separate methods for these adds no value and only detracts from our solution. That’s where lambda methods come in.

USING LAMBDA EXPRESSIONS

We can use lambda methods as small, inline blocks of code (which are just functions like any other) that are used directly where they are called. Here’s the same thing with lambdas (notice no other check method):

find_special_numbers(lambda i: i % 2 == 1, 25)

Nice huh? Lambdas solve a bunch of problems elegantly in Python. Check out this video to see them in action!