Lambda Function in Python: Complete Guide for Developers
Updated on Oct 29, 2025 | 7 min read | 6.54K+ views
Share:
For working professionals
For fresh graduates
More
Updated on Oct 29, 2025 | 7 min read | 6.54K+ views
Share:
Table of Contents
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.
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
A lambda function can take any number of arguments, but it can only contain one expression.
Popular Data Science Programs
# Regular function
def add(x, y):
return x + y
# Lambda equivalent
add_lambda = lambda x, y: x + y
print(add_lambda(5, 3))
Output: 8
Both versions work the same way, the second one just uses the lambda keyword to make it shorter.
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:
Also Read: Most Important Python Functions [With Examples] | Types of Functions
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.
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
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 |
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)
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().
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
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.
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.
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.
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).
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: 8
This returns the greater of two numbers without using an if statement block.
Also Read: Understanding List Methods in Python with Examples
These are the most common use cases for lambda functions in Python.
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]
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.
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 | A |
| Aisha | 90 | A |
| Janvi | 78 | B |
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
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.
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.
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)
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 |
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)
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.
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
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
Yes, but it’s not recommended. Nested lambdas make code difficult to read and debug. Always prioritize clarity over compactness in such cases.
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.
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
By submitting, I accept the T&C and
Privacy Policy
Start Your Career in Data Science Today
Top Resources