## Introduction

*For* loops are the antithesis of efficient programming. They’re still necessary and are the first conditional loops taught to Python beginners but in my opinion, they leave a lot to be desired.

These *for* loops can be cumbersome and can make our Python code bulky and untidy. But wait – what’s the alternative solution? Lambda functions in Python!

Lambda functions offer a dual boost to a data scientist. You can write tidier Python code and speed up your machine learning tasks. The trick lies in mastering lambda functions and this is where beginners can trip up.

Initially, I also found lambda functions difficult to understand. They are short in length yet can appear confusing as a newcomer. But once I understood how to use them in Python, I found them very easy and powerful. And I’m sure you will as well by the end of this tutorial.

So in this article, you’ll be learning about the power of lambda functions in Python and how to use them. Let’s begin!

*Note: New to Python? I highly recommend checking out the below free courses to get up to scratch:*

## What are Lambda Functions?

A lambda function is a small function containing a single expression. Lambda functions can also act as anonymous functions where they don’t require any name. These are very helpful when we have to perform small tasks with less code.

We can also use lambda functions when we have to pass a small function to another function. Don’t worry – we’ll cover this in detail soon when we see how to use lambda functions in Python.

Lambda functions were first introduced by Alonzo Church in the 1930s. Mr. Church is well known for lambda calculus and the Church-Turing Thesis.

Lambda functions are handy and used in many programming languages but we’ll be focusing on using them in Python here. In Python, lambda functions have the following syntax:

Lambda functions consist of three parts:

- Keyword
- Bound variable/argument, and
- Body or expression

The keyword is mandatory, and it must be a **lambda**, whereas the arguments and body can change based on the requirements. You must be wondering why you should go for lambda functions when you have other regular functions. Fair question – let me elaborate on this.

**Comparing Lamba Functions with Regular Functions**

Lambda functions are defined using the keyword **lambda**. They can have any number of arguments but only one expression. A lambda function cannot contain any statements, and it returns a function object which can be assigned to any variable. *They are generally used for one-line expressions.*

Regular functions are created using the **def** keyword. They can have any number of arguments and any number of expressions. They can contain any statements and are generally used for large blocks of code.

**IIFEs using lambda functions**

IIFEs are Immediately Invoked Function Expressions. These are functions that are executed as soon as they are created. IIFEs require no explicit call to invoke the function. In Python, IIFEs can be created using the lambda function.

Here, I have created an IIFE that returns the cube of a number:

`(lambda x: x*x*x)(10)`

Awesome!

**Application of Lambda Functions with Different Functions**

Time to jump into Python! Fire up your Jupyter Notebook and let’s get cracking.

Here, I have created a random dataset that contains information about a family of 5 people with their id, names, ages, and income per month. I will be using this dataframe to show you how to apply lambda functions using different functions on a dataframe in Python.

df=pd.DataFrame({ 'id':[1,2,3,4,5], 'name':['Jeremy','Frank','Janet','Ryan','Mary'], 'age':[20,25,15,10,30], 'income':[4000,7000,200,0,10000] })

**Lambda with Apply**

Let’s say we have an error in the age variable. We recorded ages with a difference of 3 years. So, to remove this error from the Pandas dataframe, we have to add three years to every person’s age. We can do this with the **apply()** function in Pandas.

**apply()** function calls the lambda function and applies it to every row or column of the dataframe and returns a modified copy of the dataframe:

df['age']=df.apply(lambda x: x['age']+3,axis=1)

We can use the** apply() **function to apply the lambda function to both rows and columns of a dataframe. If the **axis** argument in the **apply()** function is 0, then the lambda function gets applied to each column, and if 1, then the function gets applied to each row.

**apply()** function can also be applied directly to a Pandas series:

df['age']=df['age'].apply(lambda x: x+3)

Here, you can see that we got the same results using different methods.

### Lambda with Filter

Now, let’s see how many of these people are above the age of 18. We can do this using the **filter()** function. The **filter()** function takes a lambda function and a Pandas series and applies the lambda function on the series and filters the data.

This returns a sequence of **True** and **False,** which we use for filtering the data. Therefore, the input size of the **map()** function is always greater than the output size.

`list(filter(lambda x: x>18,df['age']))`

### Lambda with Map

You’ll be able to relate to the next statement. 🙂 It’s performance appraisal time and the income of all the employees gets increased by 20%. This means we have to increase the salary of each person by 20% in our Pandas dataframe.

We can do this using the **map()** function. This **map()** function maps the series according to input correspondence. It is very helpful when we have to substitute a series with other values. In **map()** functions, the size of the input is equal to the size of the output.

`df['income']=list(map(lambda x: int(x+x*0.2),df['income']))`

### Lambda with Reduce

Now, let’s see the total income of the family. To calculate this, we can use the **reduce()** function in Python. It is used to apply a particular function to the list of elements in the sequence. The **reduce()** function is defined in the **‘functools’** module.

For using the **reduce()** function, we have to import the **functools** module first:

import functools functools.reduce(lambda a,b: a+b,df['income'])

**reduce()** function applies the lambda function to the first two elements of the series and returns the result. Then, it stores that result and again applies the same lambda function to the result and the next element in the series. Thus, it reduces the series to a single value.

**Note:** Lambda functions in **reduce()** cannot take more than two arguments.

**Conditional Statements using Lambda Functions**

Lambda functions also support conditional statements, such as if..else. This makes lambda functions very powerful.

Let’s say in the family dataframe we have to categorize people into ‘Adult’ or ‘Child’. For this, we can simply apply the lambda function to our dataframe:

`df['category']=df['age'].apply(lambda x: 'Adult' if x>=18 else 'Child')`

Here, you can see that Ryan is the only child in this family, and the rest are adults. That wasn’t so difficult, was it?

**What’s Next?**

Lambda functions are quite useful when you’re working with a lot of iterative code. They do appear complex, I understand, but I’m sure you’ll have grasped their importance in this tutorial.

Do share this article and comment below in case you have any queries or feedback. Here, I have listed some in-depth blogs and courses related to data science and Python:

**Courses:**

- Python for Data Science
- Data Science Hacks, Tips and Tricks
- Introduction to Data Science
- A comprehensive Learning path to become a data scientist in 2020

**Blogs:**

- Comprehensive learning path – Data Science in Python
- How to use loc and iloc for Selecting Data in Pandas (with Python code!)

can you share an example for ‘for’ loop using lambda function

You can use map() or apply() function to achieve similar functionality i.e., to iterate over elements of an array or list. For example,

x = [1, 2, 3, 4, 5]

y=list(map(lambda i: i*i,x))

Now, y is an array containing square to elements in x.

[1, 4, 9, 16, 25]