A Simple Introduction of the Lambda Function in Python

In my “Coffee Break Python” email series, my readers can ask me any Python related questions. This is the question of one of my active readers Prashant asked regarding the important lambda function in Python:

Is there any in-depth demonstration of lambda function apart from documentation? I’ve seen the lambda function a lot of times, more than anything in Python. I want to understand it’s proper arrangement and many other features.


To this end, I created a small video introducing the lambda function in detail:

def make_incrementor(n):
   return lambda x: x + n
f = make_incrementor(42)

To test your understanding, you can solve this exact code puzzle with the topic “lambda functions in Python” at my Finxter code puzzle app.

When to use lambda functions?

Another Finxter user Collen asked:

If you don’t mind, can you please explain, with examples, how we are supposed to use ‘lambda’ in our Python programming codes?”.

Lambda functions are anonymous functions that are not defined in the namespace (they have no names). The syntax is:

lambda <argument name> : <return expression>.

First of all, don’t use lambda functions if it doesn’t feel natural. In contrast to many other Python coders, I’m no big fan of creating fancy Pythonic code that nobody understands.

Having said this, I must admit that I use lambda functions quite frequently. Here is how I use lambda functions in one of my puzzles (you may recognize it from the CBP book).

def encrypt(s1):
    s2 = map(lambda c : chr(ord(c) + 2), s1)
    return ''.join(s2)

def decrypt(s1):
    s2 = map(lambda c : chr(ord(c) - 2), s1)
    return ''.join(s2)

s = "xtherussiansarecomingx"

What’s the output of this code?

The encrypt function shifts the string by two Unicode positions to the right. The decrypt function does the exact opposite shifting the string s1 to the left. Hence, the output is “True”.

To answer the question, I use lambda functions only as an input argument for functions such as map() or filter(). For example, the map function applies the argument function (anonymous or not – doesn’t matter) to each element of a sequence. But it’s often cleaner to define the function first and giving it a human-readable name.

Leave a Comment