top of page
learn_data_science.jpg

Data Scientist Program

 

Free Online Data Science Training for Complete Beginners.
 


No prior coding knowledge required!

Writer's pictureSujan Karki

Python Concepts for Data Science: Lambda Functions

Functions are a handy tool whenever we want to perform a repetitive task. It helps us by preventing to write the same section of codes over and over again. However, situations can arise when we want to define a function for a single use. Like for example, a function such as:

def plus_one(x):
    return x+1

One can argue why define such single line functions. The answer would be because some functions such as map(), filter(), etc. required a function as an argument.


A lambda function thus allows us to define a single line, readable and temporary function for such use. The above specified plus_one() function can be written as a lambda function as

plus_one = lambda x: x+1 

However note that, although a variable name can be assigned for lambda function, it is not a good practice to do so. A lambda function is thus also known as a 'Anonymous function' i.e. a function without a name.


Syntax

lambda arguments: expression

The syntax of lambda function is the keyword lambda followed by the argument. Then comes the expression separated from argument by the : (colon) sign.


To get a better understanding of the lambda function, lets look at a few examples.


Example 1: use with filter()

The filter() function in Python takes in a function and a list as arguments.

The function is called with all the items in the list and a new list is returned which contains items for which the function evaluates to True. Here is an example use of filter() fun