Lambda Function

Abhishek Mani
2 min readApr 11, 2021

A lambda function is small anonymous function . A lambda function can take any number of arguments , but only one expression. A lambda expression is used when a calling function (or class) that accept a function as argument.

The pros and cons of lambda :

  1. They can be immediately passed around (no variable are used
  2. They can only have a single line of code within them
  3. They return automatically
  4. They can’t have a docstring and can’t have a name

Biggest reason lambda expressions are used that lambda functions can be passed around in any function

When should we use lambda :

  1. When you don’t see an appropriate name for any small function then use it
  2. When your development team agrees upon using lambda as lambda expression can be difficult to debug in case when get any error as you will only get generic error regarding this lambda doesn’t have a name

Lambda misused and overused :

Example : if we create a lambda expression shown as below-

upper_case = lambda name : name.upper()

this above code is anonymous function and it assigns to a variable . The above code ignores the reason lambda function are useful

the above code is similar to :

def upper_case(name):
return name.upper()

Misuse and needless function call :

lets understand it with a example:

numbers = [44,33,22,11,55,32] #list of numbers
sorted_numbers = sorted(numbers, key=lambda num:abs(num))
using lambda in above way makes no sense we can use it directly in following way :
sorted_numbers = sorted(numbers, key=abs)

Overuse :simple but non-trivial functions:

colors = ["red","blue","green","yellow"]
#sorting based on length and alphabetical
sorted_colors = sorted(colors, key=lambda col: (len(col),col.casefold()))
# or we can do this in another way as shown below
def length_and_alphabetical(color):
return (len(color),color.casefold())
sorted_colors = sorted(colors,key=length_and_alphabetical)

the difference between above two code is we are trying to sort list based on the length and alphabetical . using lambda in sorted making it not much readable whereas creating another function is more readable .

Overuse : when multiple lines could help:

points = [((1,2),'red'),((3,4),'blue')]
points_by_color = sorted(points, key = lambda point:point[1])
# writing the above using a function
def color_of_point(point):
(x,y),color = point
sorted_color = sorted(points, key=color_of_point)

Misuse : Sometime we don’t even need to pass a function:

from functools import reducenumbers = [1,2,3,4,5]
sum_total = reduce(lambda x,y:x+y,numbers)
# the above task can easily be achieved by usingsum_total = sum(numbers)

Thank you!

--

--

Abhishek Mani

I am software developer , experienced in python web app development , javascript , data science