Lambda Functions in Python: A Simple Introduction

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

This question was asked in my “Coffee Break Python” email series. Watch the video or read the small article to learn about lambda functions in Python:

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

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?

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

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"
print(decrypt(encrypt(encrypt(s)))==encrypt(s))

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

Your email address will not be published. Required fields are marked *