Lambda Function in Python: Complete Guide for Developers

By Pavan Vadapalli

Updated on Oct 29, 2025 | 7 min read | 6.54K+ views

Share:

A lambda function in Python is a small, anonymous function used to perform quick, one-line operations without defining a full function using def. It’s often used with higher-order functions like map(), filter(), and reduce() for data transformation, sorting, or applying inline logic. These functions help you write cleaner, faster, and more expressive Python code in fewer lines. 

In this guide, you’ll read more about the syntax and structure of lambda functions, their uses with map, filter, and reduce, practical coding examples, advanced applications in pandas, best practices to help you master this essential Python feature. 

Explore Online Data Science Courses from the World’s top Universities. Earn Executive PG Programs, Advanced Certificate Programs, or Masters Programs to fast-track your career.   

What is Lambda Function in Python? 

A lambda function in Python lets you write a function in a single line, without formally defining it. This makes  your code cleaner and more concise, especially when used inside functions like map(), filter(), and sorted(). 

Basic Syntax 

lambda arguments: expression 
  
  • lambda – the keyword that defines an anonymous function 
  • arguments – the input values (can be one or more) 
  • expression – the operation to perform and return 

A lambda function can take any number of arguments, but it can only contain one expression

Example 1: Simple Lambda Function 

# Regular function 
def add(x, y): 
    return x + y 
 
# Lambda equivalent 
add_lambda = lambda x, y: x + y 
 
print(add_lambda(5, 3))   

Output:
Both versions work the same way, the second one just uses the lambda keyword to make it shorter. 

Why Use Lambda Functions? 

Lambda functions are handy when you need a small, temporary function for short tasks. They are not meant to replace normal functions but are useful when: 

  • You need a function just once or for a short operation. 
  • You want to keep your code compact and readable. 
  • You’re using functions that expect another function as input (like map(), filter(), reduce()). 

Also Read: Most Important Python Functions [With Examples] | Types of Functions 

Example 2: Using Lambda with map() 

numbers = [1, 2, 3, 4, 5] 
squared = list(map(lambda x: x**2, numbers)) 
print(squared) 
  

Output: [1, 4, 9, 16, 25] 
Here, the lambda function lambda x: x**2 quickly squares each element without needing a separate function definition. 

Example 3: Using Lambda with filter() 

numbers = [10, 15, 20, 25, 30] 
even = list(filter(lambda x: x % 2 == 0, numbers)) 
print(even) 
  

Output: [10, 20, 30] 
The lambda function filters numbers that are divisible by 2. 

Data Science Courses to upskill

Explore Data Science Courses for Career Progression

background

Liverpool John Moores University

MS in Data Science

Double Credentials

Master's Degree17 Months

Placement Assistance

Certification6 Months

Comparison: Regular Function vs Lambda Function 

Feature 

Regular Function 

Lambda Function 

Defined using  def keyword  lambda keyword 
Has a name  Yes  No 
Can have multiple expressions  Yes  No 
Common use case  General-purpose reusable code  Small, short-lived operations 
Syntax length  Multiple lines  One line 

Key Points to Remember 

  • A lambda function can have multiple parameters but only one expression. 
  • It returns the result of the expression automatically, no return keyword needed. 
  • Best suited for inline operations or when used with higher-order functions like map(), filter(), or sorted(). 
  • Not ideal for complex logic or reusable code. 

In short, lambda functions in Python let you create short, simple functions on the go. They help reduce code clutter and are especially useful in functional programming tasks. 

Also Read: Top 7 Python Data Types: Examples, Differences, and Best Practices (2025) 

Use of Lambda Function in Python 

A lambda function in Python is used when you need a quick, one-line function for simple operations. It helps make your code cleaner and avoids unnecessary function definitions. 

You’ll often use lambda functions when passing small functions as arguments to other functions like map(), filter(), or sorted(). 

Common Uses of Lambda Functions 

1. With map() – Apply a function to each element 

numbers = [1, 2, 3, 4, 5] 
doubled = list(map(lambda x: x * 2, numbers)) 
print(doubled) 
  

Output: [2, 4, 6, 8, 10] 

 Here, the lambda function doubles each number in the list. 

2. With filter() – Select items that meet a condition 

numbers = [10, 15, 20, 25, 30] 
even = list(filter(lambda x: x % 2 == 0, numbers)) 
print(even) 
  

Output: [10, 20, 30] 

 This keeps only the even numbers using a short lambda expression. 

3. With sorted() – Custom sorting logic 

words = ["apple", "banana", "cherry", "date"] 
sorted_words = sorted(words, key=lambda x: len(x)) 
print(sorted_words) 
  

Output: ['date', 'apple', 'banana', 'cherry'] 

 Here, the lambda function sorts words based on their length. 

Also Read: How to Use Sort in Python: Methods, Parameters, and Examples 

Summary Table 

Function 

Use Case 

Example 

map()  Transform data  Multiply numbers by 2 
filter()  Filter elements  Keep even numbers 
sorted()  Custom sorting  Sort by length or value 

In short, you use lambda functions in Python when you want a short, throwaway function that performs a simple task inline without defining it separately. 

Practical Examples of Lambda Function in Python 

The lambda function in Python is one of the most useful tools for writing quick, compact logic without creating a full function. Let’s look at some practical examples that show how you can use it in real-world scenarios. 

1. Basic Mathematical Operations 

You can use a lambda function for quick arithmetic tasks. 

add = lambda x, y: x + y 
multiply = lambda x, y: x * y 
 
print(add(10, 5)) 
print(multiply(4, 3)) 
  

Output: 

 15 

 12 

This makes your code cleaner when performing simple calculations on the fly. 

2. Sorting Lists of Tuples 

When sorting lists with multiple values, you can use a lambda to define how sorting should happen. 

students = [("Ramesh", 22), ("Aisha", 20), ("Jahanvi", 23)] 
sorted_students = sorted(students, key=lambda x: x[1]) 
print(sorted_students) 
  

Output:  [(Ramesh ', 20), (‘Aisha ', 22), (‘Jahanvi ', 23)] 

Here, the list is sorted based on the student’s age (the second element). 

3. Conditional Expressions 

Lambda functions can also handle conditional logic in one line. 

max_num = lambda a, b: a if a > b else b 
print(max_num(8, 5)) 
  

Output:

This returns the greater of two numbers without using an if statement block. 

Also Read: Understanding List Methods in Python with Examples 

4. Working with map() and filter() 

These are the most common use cases for lambda functions in Python. 

  • map() applies a function to every item in a list. 
  • filter() keeps only the items that meet a condition. 
numbers = [1, 2, 3, 4, 5] 
squares = list(map(lambda x: x**2, numbers)) 
evens = list(filter(lambda x: x % 2 == 0, numbers)) 
print(squares) 
print(evens) 
  

Output: 

 [1, 4, 9, 16, 25] 

 [2, 4] 

5. Using reduce() for Aggregation 

The reduce() function (from functools) applies a lambda cumulatively to all elements. 

from functools import reduce 
product = reduce(lambda x, y: x * y, [1, 2, 3, 4]) 
print(product) 
  

Output:  24 

This multiplies all numbers in the list together. 

6. Lambda with pandas 

Lambda functions are widely used in data manipulation with the pandas library. 

import pandas as pd 
 
data = {'Name': ['Ramesh', 'Aisha', 'Janvi'], 'Marks': [85, 90, 78]} 
df = pd.DataFrame(data) 
df['Grade'] = df['Marks'].apply(lambda x: 'A' if x > 80 else 'B') 
print(df) 
  

Output: 

Name 

Marks 

Grade 

Ramesh  85 
Aisha  90 
Janvi  78 

Here, the lambda function assigns grades based on marks,  a clean and efficient way to apply logic across rows. 

Also Read: Python Pandas Tutorial: Everything Beginners Need to Know about Python Pandas 

Summary 

Example Type 

Description 

Function Used 

Arithmetic  Perform basic math  lambda x, y: x + y 
Sorting  Sort tuples or lists  sorted() 
Conditional  Return values based on logic  if-else 
Mapping  Apply function to items  map() 
Filtering  Select matching items  filter() 
Aggregation  Combine all items  reduce() 
Data Manipulation  Row-level operations  pandas apply() 

These practical examples of lambda function in Python show how it simplifies repetitive coding tasks and makes your programs more concise and readable. 

Best Practices and Common Mistakes Using Lambda Function in Python 

A lambda function in Python can make your code more compact and readable, but if used incorrectly, it can also make it harder to understand. Knowing when and how to use lambda functions is key to writing clean, maintainable Python code. 

Let’s go through the best practices and some common mistakes developers make when using lambda functions. 

Best Practices 

1. Keep lambda functions short 

 Use lambda only for simple, single-line operations. If your logic needs multiple conditions or statements, define a normal function with def. 

# Good 
square = lambda x: x * x 
 
# Avoid 
complex_fn = lambda x: (x ** 2 + 3 * x - 5) / (x - 1) if x != 1 else 0 
  

Simple functions are easier to read and debug. 

Also Read: Control Flow Statements in Python 

2. Use them with built-in functions wisely 

 Lambda functions are most powerful when used with map(), filter(), sorted(), and reduce()

 They help you write quick transformations without defining extra functions. 

Example: 

nums = [1, 2, 3, 4, 5] 
doubled = list(map(lambda x: x * 2, nums)) 
  

3. Add context with variable names 

 If the same lambda logic is used multiple times, assign it to a named variable. This improves readability. 

get_square = lambda x: x ** 2 
print(get_square(5)) 
  

Now the purpose of the function is clear. 

4. Combine with pandas for quick data operations 

 In data analysis, you can use lambda inside the apply() method to handle row or column transformations efficiently. 

df['Discount'] = df['Price'].apply(lambda x: x * 0.1) 
  

Common Mistakes to Avoid 

Mistake 

Description 

Example 

Using lambdas for complex logic  Makes code unreadable and hard to debug  lambda x: (x**2 + 3*x - 5)/(x-1) if x!=1 else 0 
Ignoring readability  Too many inline lambdas make code confusing  Using nested lambdas inside list comprehensions 
Using them unnecessarily  Sometimes a normal function is clearer  Replacing simple loops with multiple lambdas 
Forgetting scope limitations  Lambda can’t contain statements like return or print()  lambda x: print(x) won’t work as expected 

When to Use Lambda Functions 

  • When you need a temporary, one-line function
  • When passing a simple operation to another function. 
  • When working with iterables in map(), filter(), or sorted()
  • When performing data transformations in pandas or NumPy

When to Avoid Lambda Functions 

  • When logic requires multiple steps or conditions
  • When code needs to be reused in multiple places. 
  • When readability is more important than compactness. 

By following these best practices, you’ll make your code both concise and readable. The lambda function in Python is a great tool when used correctly, keep it simple, use it with context, and avoid overcomplicating your logic. 

Also Read: The Ultimate Guide to Python Challenges for Beginners (2025) 

Comparing Alternatives: Lambda vs Regular Function 

Both lambda functions and regular functions serve the same purpose, performing operations, but they differ in structure, readability, and use cases. Understanding when to use each helps you write cleaner and more efficient Python code. 

Feature 

Lambda Function 

Regular Function 

Syntax  Single line  Multi-line 
Keyword  lambda  def 
Name  Anonymous  Has a defined name 
Readability  Best for simple logic  Better for complex logic 
Use Case  Inline operations  Reusable logic 

 Use a lambda function in Python for short, simple operations inside other functions. Choose a regular function when your logic needs clarity, multiple steps, or reuse across your project. 

Conclusion 

Lambda functions in Python are best for quick, one-line tasks that make code concise and efficient. They work well for temporary or inline logic, especially with functions like map(), filter(), and sorted(). Regular functions, on the other hand, are better for complex logic, debugging, and reusability. Choosing between the two depends on your goal — use lambda for simplicity and speed, and regular functions when you need structure, clarity, or multiple lines of logic. 

Subscribe to upGrad's Newsletter

Join thousands of learners who receive useful tips

Promise we won't spam!

Frequently Asked Questions (FAQs)

1. What is a lambda function in Python?

 A lambda function in Python is a small, anonymous function used for short, single-line operations. It’s defined using the lambda keyword and is often used with built-in functions like map(), filter(), and sorted() to simplify code. 

2. Why are lambda functions called anonymous in Python?

 They’re called anonymous because they don’t have a defined name like regular functions created with def. A lambda function performs its task inline, often passed as an argument within other functions. 

3. What is the syntax of a lambda function in Python?

 The syntax is simple: lambda arguments: expression. You can use it to perform operations without defining a complete function. For example, lambda x: x * 2 doubles a number when called. 

4. When should you use a lambda function in Python?

 Use a lambda function when you need a short, throwaway function for simple logic. It’s perfect for quick transformations, filtering, or sorting tasks that don’t require multiple lines of code. 

5. What is the difference between a lambda function and a regular function?

 A lambda function is defined in one line without a name, while a regular function uses def and can contain multiple statements. Lambda functions are best for small, inline tasks, while regular ones handle complex logic. 

6. Can a lambda function have multiple arguments?

 Yes, a lambda function can take multiple arguments separated by commas. For example, lambda x, y: x + y adds two numbers. But it can only have a single expression in its body. 

7. Can a lambda function in Python contain multiple expressions?

 No, a lambda function can only contain one expression. It cannot include statements or multiple operations. If your logic needs several steps, use a regular def function instead. 

8. How do you use a lambda function with map()?

 The map() function applies a lambda to each item in an iterable. Example: 

numbers = [1, 2, 3] 
result = list(map(lambda x: x * 2, numbers)) 
 This doubles every number in the list. 

9. How do you use a lambda function with filter()?

 The filter() function uses lambda to select elements that meet a condition. Example: 

nums = [1, 2, 3, 4] 
evens = list(filter(lambda x: x % 2 == 0, nums)) 
This keeps only even numbers. 

10. How do you use lambda functions with sorted()?

You can use a lambda function as the key parameter in sorted(). Example: 

words = ['apple', 'kiwi', 'banana'] 
sorted(words, key=lambda x: len(x)) 
This sorts words by their length. 

11. Can a lambda function return multiple values?

 No, a lambda function returns only one value — the result of its single expression. If you need to return multiple values or complex structures, use a regular function. 

12. Are lambda functions faster than regular functions?

 Performance-wise, both are nearly identical. The main advantage of lambda functions is concise syntax, not speed. They help make short, readable operations cleaner within your code. 

13. Can you assign a lambda function to a variable?

 Yes, you can assign a lambda function to a variable for reuse. Example: 

square = lambda x: x * x 
print(square(5)) 
This stores the function in square and calls it like any regular function. 

14. Can a lambda function use default arguments?

 Yes, you can define default arguments in a lambda function. Example: 

add = lambda x, y=2: x + y 
print(add(5)) 
This adds 5 and 2 by default unless another value is provided. 

15. Can lambda functions access variables outside their scope?

 Yes, they can access variables from their enclosing scope. For example: 

multiplier = 3 
triple = lambda x: x * multiplier 
Here, lambda uses the outer variable multiplier for its calculation. 

16. What are common mistakes when using lambda functions in Python?

 Common mistakes include using lambdas for complex logic, writing unreadable inline code, and assuming they can hold multiple statements. Keep them short and focused on one task. 

17. Can you use conditional statements in a lambda function?

Yes, but only in a single-line conditional expression. Example: 

max_num = lambda a, b: a if a > b else b 
This returns the greater of two values. 

18. How are lambda functions used in pandas?

 In pandas, lambda functions simplify data transformations. For example: 

df['Discount'] = df['Price'].apply(lambda x: x * 0.1) 
 This applies a 10% discount to all price values. 

19. Can you nest lambda functions in Python?

 Yes, but it’s not recommended. Nested lambdas make code difficult to read and debug. Always prioritize clarity over compactness in such cases. 

20. What is the main use of lambda function in Python?

 The main use of lambda function in Python is for writing short, anonymous functions that make your code cleaner. They’re ideal for functional programming tasks like mapping, filtering, and sorting data efficiently. 

Pavan Vadapalli

907 articles published

Pavan Vadapalli is the Director of Engineering , bringing over 18 years of experience in software engineering, technology leadership, and startup innovation. Holding a B.Tech and an MBA from the India...

Speak with Data Science Expert

+91

By submitting, I accept the T&C and
Privacy Policy

Start Your Career in Data Science Today

Top Resources

Recommended Programs

IIIT Bangalore logo
bestseller

The International Institute of Information Technology, Bangalore

Executive Diploma in DS & AI

360° Career Support

Executive PG Program

12 Months

Liverpool John Moores University Logo
bestseller

Liverpool John Moores University

MS in Data Science

Double Credentials

Master's Degree

17 Months

upGrad Logo

Certification

3 Months