You are currently viewing Lambda expression in Python

Lambda expression in Python

Loading

Hello guys, I hope everyone is doing well. In this blog, we’ll talk about lambda expressions, which are essentially unnamed functions called anonymous functions.

Let’s first learn what function signifies in coding before diving into a lambda expression.

Functions in Python

In a programming language, a function is a block of code that contains a few structured lines of code, executes when executed, and can be called multiple times. The block can be used at any moment and completes a specific task.

#This function adds two numbers 
def add(num1, num2):
    addition = num1 + num2 
    return addition
    
add(5,7)

The term “def” is used to define functions, which can thereafter be called with either defined or undefined parameters; basically, it creates a function and the function body. The value is printed using the “return” statement at the end. As a result, any Python function can be utilized with the above-described technique.

Types of functions

I believe we have a solid idea of how the function operates based on the prior description, and we’ll look at how functions are categorized here.

  • User-Defined Function- A function’s customary writing style
  • Built-in Function- Uncustomizable; must be used exactly as it is delivered.

The example we just saw was a user-defined function, and Python also has built-in function examples such as int(), input(), float(), min(), and many more.

In Python, the lambda keyword is used to define anonymous functions rather than the def keyword, which is used for conventional functions. Since they are frequently used interchangeably, lambda functions are also sometimes referred to as anonymous functions.

Syntax for lambda function is quite simple

lambda arguments: expressions

Running a lambda function that assesses its expression and then promptly returns its result is the fundamental benefit of employing lambdas. So, a return statement is always implied. Because of this, lambdas are sometimes known as single-expression functions. Coding language features that help to simplify code are quite helpful in most situations.

Lambda functions are generally beneficial, but you should think twice before using them if doing so results in longer-than-expected single-line code that is difficult to read for the user. Basically, as your code becomes less readable, you should think about not using lambda functions.

The above function we saw could be easily written as such

f = lambda x,y: x + y
f(5,7)

Applying lambda function on a dataset

Lambda functions are frequently combined with other functions to complete complicated tasks in a few lines of code as opposed to a lengthy block. These are the filter, map, and reduce operations. Let’s examine each of them separately using distinct problem statements.

#importing libraries
import pandas as pd

#creating dataframe
data = pd.DataFrame({
    'S.No':[1,2,3,4,5],
    'Name':['Abhijeet','Prakash','Sagar','Dibyen','Ritu'],
    'Expert':['Mould','Programming','Camera','Machine','English'],
    'Income':[25000,50000,30000,18000,24000],
    'Place':['Chennai','Bhubaneswar','Delhi','Daman','Mysore'],
    'Experience':[3,2,7,9,5]
})

data

Let us say we want to increment the income of each person by Rs 10000

Using apply function incorporated with lambda to get a desirable update in our dataframe.

# after one year there salary has been raised by 10000
data['Income'] = data.apply(lambda K: K['Income']+10000, axis=1) 

data['Experience'] = data.apply(lambda K: K['Experience']+1, axis=1)
data

Lambda function with filter()

The filter() function, as the title suggests, will construct a new list and save just the elements that satisfy a given criterion and will filter out the remaining values.

An Iterable and a function object are both required for the filter() method to build a new list. Every time the condition is met and the result is true, the calculation is considered successful.

#filter function for segregation from the dataframe who have experience more than years in their respective domains

output = list(filter(lambda i: i>7, data['Experience']))7 
print(output)
[8, 10]

Lambda function with map()

The function we gave as a parameter is applied to each item in the given iterable as the map() method iterates through all of its elements. This is equivalent to the filter() function.

It can be used to map every element to its corresponding output or to acquire true and false Boolean values for each item on the conditional list. Let’s use some code to clarify this in greater depth.

#doing some basic arithmetic operations
a = [70, 90, 85, 40, 59] 
ope = list(map(lambda x: x * 0.5 + x, a))
print(ope)

-----> [105.0, 135.0, 127.5, 60.0, 88.5]

Lambda function with reduce()

The reduce function operates somewhat differently than the filter and map functions. It proceeds to return only one value after going through the list of iterable numbers.

Up until the end of the iterable, the reduce() function computes the list of two elements at a time.

import functools
# Getting the info about the total years of experience of all candidates
functools.reduce(lambda p,q: p+q,data['Experience']) 

-----> 31

The Lambda function can be combined with the if-else loop

Let us understand this with the code below:

data['Category']=data['Experience'].apply(lambda x: 'Experienced' if
  x>=5 else 'Fresher')

data

As we can observe that new column is added to the dataframe implying that the candidate is a newcomer or an experienced one.

Disadvantages of the lambda function

  • Despite being the most widely used programming language in the world, Python; the Lambda function may not be not user-friendly in certain cases.
  • If we need to construct a complex function, the Lambda function will pose a problem.
  • It can access a single local variable; it is unable to access a global variable.
  • There are some situations where the Lambda function’s single statement flexibility is not appropriate.
  • Entirely limited to a single expression.

Conclusion

We learned a little bit about the fundamentals of how functions work in the Python programming language.

Then we continued our discussion of Python’s anonymous function, understanding each of its advanced function options with some codes and examples, and finally looking at some of the disadvantages of lambda functions. In the following step, I urge you to experiment with and examine various datasets and try to analyze how effective it will be to use lambda functions. Thank you for reading this long. I sincerely value your constructive feedback and suggestions as I strive to get better.

This Post Has One Comment

  1. Prachi Singh

    A very well written post

Comments are closed.