Coder's Cat

Python: Pros and Cons of Lambda



Basics for lambda

lambda is a keyword in Python. We use it to create an anonymous function. So we also call lambda functions as anonymous functions.

But what is the anonymous function?

A normal function defined like this:

def sum_two(x, y):
x + y


#<function sum_two at 0x10f54eb18>
#<type 'function'>

From the result, sum_two is the name of the defined function, it’s type is ‘function’.

Compared to normal function, an anonymous function is a function without a user-defined name.

Anonymous people sometimes get generic names such as ‘Anonymous’ or ‘Jane Doe’. In CPython, lambda functions get the generic pseudoname ‘’, used for repr() and tracebacks:

print(lambda x, y: x + y)
print(type(lambda x, y: x + y))

#<function <lambda> at 0x108227f50>
#<type 'function'>

(lambda: 0).__name__
# '<lambda>'

The benefits of lambda

But why we want to give a generic pseudo-name to some functions?

Naming is too damn hard! Think about how much time you spent on naming(variables, functions, classes) when you are programming.

Not all functions deserved a user-defined name.

Some functions are used temporarily, and we won’t need them later. We use a lambda function to saving time for naming and get better readability.

Suppose we need to add 2 to each element in a list, instead of use normal function:

def add_2(x):
return x + 2

lst = [3,5,-4,-1,0,-2,-6]
map(add_2, lst)

We could use lambda to finish the same computation in one line:

map(lambda x: x + 2, lst)

This is simplicity. We can write a lambda function with no hassle.

There are other functions like filter, reduce, sorted, they receive lambda function as a parameters.

The pitfall of lambda

The purpose of lambda function is to improve the code’s readability. So if the logic of a function is not simple, we should not use lambda.

A simple rule is: don’t use lambda for the functions whose lengths are more than one line.

Think about this code snippet, could you understand this code easily?

f = lambda x: [[y for j, y in enumerate(set(x)) if (i >> j) & 1] for i in range(2**len(set(x)))]

This code is difficult to understand. The intention of this code is to get all the subsets from a set.

a = {1, 2, 3}
# [[], [1], [2], [1, 2], [3], [1, 3], [2, 3], [1, 2, 3]]

In this case, we should use a normal function with a proper name:

def powerset(s):
N = len(s)
result = []
for i in range(2 ** N):
combo = []
for j, y in enumerate(s):
if (i >> j) % 2 == 1:
return result



Explicit is better than implicit.
Zen of Python

Remember, if we can’t make code clearer and shorter with lambda functions, then we need to use conventional ways to define functions.

Tags: Python