VOOZH about

URL: https://www.analyticsvidhya.com/blog/2020/03/what-are-lambda-functions-in-python/

⇱ Lambda Functions In Python | Easy & Effective Ways to Use Them


India's Most Futuristic AI Conference Is Back – Bigger, Sharper, Bolder

  • d
  • :
  • h
  • :
  • m
  • :
  • s

Learn How to Use Lambda Functions in Python Easily and Effectively

Abhishek Sharma Last Updated : 01 Dec, 2024
7 min read

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 much 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? Python Lambda Functions!

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 to a newcomer. However, once I understood how to use Python, I found them very easy and powerful. And I’m sure you will by the end of this tutorial.

👁 lambda functions in python

Learning Objectives

  • In this Python tutorial, you’ll learn about the power of lambda functions in Python programming.
  • You will learn how to use them with some built-in functions.
  • You will also learn the difference between normal functions and lambda functions.

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

Table of Contents

  1. What Are Lambda Functions?
  2. Comparing Lambda Functions With Regular Functions
  3. IIFEs Using Lambda Functions in Python
  4. Application of Lambda Functions in Python
  5. Conditional Statements Using Lambda Functions
  6. Conclusion
  7. Frequently Asked Questions

What Are Lambda Functions?

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

We can also use lambda functions when passing 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.

Alonzo Church first introduced lambda functions 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 y : x

here the lambda function takes argument y, evaluates it, and return x

👁 lambda function

Lambda functions consist of three parts:

  • Lambda Keyword
  • Bound variable/lambda argument, and
  • Body or lambda 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 Lambda Functions With Regular Functions

👁 lambda function vs normal function

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 returns a function object that can be assigned to any variable. They are generally used for one-line expressions.

Normal functions are created using the def keyword. They can have any number of arguments, expressions, and lines of code and are generally used for large blocks of code.

IIFEs Using Lambda Functions in Python

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.

Python Code:

a = (lambda x: x*x*x)(10)
print(a)

Awesome!

Application of Lambda Functions in Python

Time to jump into Python! Fire up your Jupyter Notebook, and let’s learn some use cases of lambda functions.

We can use the lambda function with some built-in functions, like the filter function, to select certain items from iterables like lists, arrays, tuples, dictionaries, etc. We can also use lambda functions in a list comprehension.

In the following example, I have created a random dataset containing 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.

Python Code:

import pandas as pd
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]
})
print(df)

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)
👁 lambda with apply | lambda functions in python

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)
👁 lambda function with apply

In the above example, you can see that we got the same results using different methods.

Lambda With Filter Function

Now, let’s see how many of these people are above 18 years. 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, and a new list is returned, which contains all the items returned by that lambda function for each item.

This returns a sequence of True and False, which we use to filter 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 filter | lambda functions in python

Lambda With Map Function

You’ll be able to relate to the next statement. It’s performance appraisal time, and the employees’ income gets increased by 20%. This means we have to increase each person’s salary 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 to substitute a series with other values. In map() functions, the input size is equal to the output size.

df['income']=list(map(lambda x: int(x+x*0.2),df['income']))
👁 lambda function with map | lambda functions in python

Lambda With Reduce Function

Now, let’s see the total income of the family. To calculate this, we can use Python’s reduce() function. 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'])

👁 lambda function with reduce | lambda functions in python

👁 reduce with lambda function in python

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.

In the family dataframe, we must 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')
👁 conditionals in lambda functions in python

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?

Conclusion

To summarize everything stated, lambda functions are a powerful tool for creating simple, one-line functions in Python. They offer a concise and readable way to define functions without needing a separate def statement. With the ability to create anonymous functions that can be passed as arguments to other functions, lambda functions can simplify code and make it more efficient. While they may not be appropriate for all situations, lambda functions can be a valuable addition to any Python programmer’s toolkit. By mastering lambda functions, you can write cleaner, more elegant code that is easier to understand and maintain.

Key Takeaways

  • Lambda functions are used to define small, one-line functions in Python. They can be used for a wide range of tasks, including filtering, mapping, and sorting data.
  • They are anonymous functions that can be used in other functions as arg or be returned as values.
  • Lambda functions can make code more efficient by eliminating the need for a separate def statement.

Frequently Asked Questions

Q1. When should I use lambda functions?

A. You can use lambda functions whenever you need a small, anonymous, and one-lined function.

Q2. Are lambda functions faster than regular functions in Python?

A. No, their performance is similar; however, lambda functions can be more efficient as there is no need for any def statement like normal functions.

Q3. Can I use lambda functions with higher-order functions?

A. Yes, you can use lambda functions with higher-order functions like filter, map, reduce, etc.

He is a data science aficionado, who loves diving into data and generating insights from it. He is always ready for making machines to learn through code and writing technical blogs. His areas of interest include Machine Learning and Natural Language Processing still open for something new and exciting.

Login to continue reading and enjoy expert-curated content.

Free Courses

Generative AI - A Way of Life

Explore Generative AI for beginners: create text and images, use top AI tools, learn practical skills, and ethics.

Getting Started with Large Language Models

Master Large Language Models (LLMs) with this course, offering clear guidance in NLP and model training made simple.

Building LLM Applications using Prompt Engineering

This free course guides you on building LLM apps, mastering prompt engineering, and developing chatbots with enterprise data.

Improving Real World RAG Systems: Key Challenges & Practical Solutions

Explore practical solutions, advanced retrieval strategies, and agentic RAG systems to improve context, relevance, and accuracy in AI-driven applications.

Microsoft Excel: Formulas & Functions

Master MS Excel for data analysis with key formulas, functions, and LookUp tools in this comprehensive course.

Responses From Readers

Shreyas B K

can you share an example for 'for' loop using lambda function

123 1
Abhishek Sharma

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]

123 456
Temitope

This is very insightful Thank you..

Flagship Programs

GenAI Pinnacle Program| GenAI Pinnacle Plus Program| AI/ML BlackBelt Program| Agentic AI Pioneer Program

Free Courses

Generative AI| DeepSeek| OpenAI Agent SDK| LLM Applications using Prompt Engineering| DeepSeek from Scratch| Stability.AI| SSM & MAMBA| RAG Systems using LlamaIndex| Building LLMs for Code| Python| Microsoft Excel| Machine Learning| Deep Learning| Mastering Multimodal RAG| Introduction to Transformer Model| Bagging & Boosting| Loan Prediction| Time Series Forecasting| Tableau| Business Analytics| Vibe Coding in Windsurf| Model Deployment using FastAPI| Building Data Analyst AI Agent| Getting started with OpenAI o3-mini| Introduction to Transformers and Attention Mechanisms

Popular Categories

AI Agents| Generative AI| Prompt Engineering| Generative AI Application| News| Technical Guides| AI Tools| Interview Preparation| Research Papers| Success Stories| Quiz| Use Cases| Listicles

Generative AI Tools and Techniques

GANs| VAEs| Transformers| StyleGAN| Pix2Pix| Autoencoders| GPT| BERT| Word2Vec| LSTM| Attention Mechanisms| Diffusion Models| LLMs| SLMs| Encoder Decoder Models| Prompt Engineering| LangChain| LlamaIndex| RAG| Fine-tuning| LangChain AI Agent| Multimodal Models| RNNs| DCGAN| ProGAN| Text-to-Image Models| DDPM| Document Question Answering| Imagen| T5 (Text-to-Text Transfer Transformer)| Seq2seq Models| WaveNet| Attention Is All You Need (Transformer Architecture) | WindSurf| Cursor

Popular GenAI Models

Llama 4| Llama 3.1| GPT 4.5| GPT 4.1| GPT 4o| o3-mini| Sora| DeepSeek R1| DeepSeek V3| Janus Pro| Veo 2| Gemini 2.5 Pro| Gemini 2.0| Gemma 3| Claude Sonnet 3.7| Claude 3.5 Sonnet| Phi 4| Phi 3.5| Mistral Small 3.1| Mistral NeMo| Mistral-7b| Bedrock| Vertex AI| Qwen QwQ 32B| Qwen 2| Qwen 2.5 VL| Qwen Chat| Grok 3

AI Development Frameworks

n8n| LangChain| Agent SDK| A2A by Google| SmolAgents| LangGraph| CrewAI| Agno| LangFlow| AutoGen| LlamaIndex| Swarm| AutoGPT

Data Science Tools and Techniques

Python| R| SQL| Jupyter Notebooks| TensorFlow| Scikit-learn| PyTorch| Tableau| Apache Spark| Matplotlib| Seaborn| Pandas| Hadoop| Docker| Git| Keras| Apache Kafka| AWS| NLP| Random Forest| Computer Vision| Data Visualization| Data Exploration| Big Data| Common Machine Learning Algorithms| Machine Learning| Google Data Science Agent
👁 Av Logo White

Continue your learning for FREE

Forgot your password?
👁 Av Logo White

Enter OTP sent to

Edit

Wrong OTP.

Enter the OTP

Resend OTP

Resend OTP in 45s

👁 Popup Banner
👁 AI Popup Banner