What is a Python lambda function?

Lambda functions in Python allow you to perform quick operations inline, making your code more concise and efficient, especially when working with higher-order functions like map(), filter(), and reduce().

Have you ever needed to perform a quick operation on a dataset without writing a full function? Lambda functions in Python allow you to do just that—offering a concise way to handle small tasks in-line with your code. Whether you're transforming data or filtering a list, lambda functions provide an elegant solution that keeps your code clean and efficient.

Lambda function

A Python lambda function is an anonymous, small function that can have any number of parameters but only one expression. The object returned by lambda is usually assigned to a variable or used as a part of other bigger functions. It is defined using the lambda keyword, unlike traditional functions defined with def. Lambda functions are ideal for simplifying short, inline tasks and are frequently used with higher-order functions like map(), filter(), and reduce() to process data efficiently.

The structure of lambda can be seen below:

Syntax of a Python lambda function
Syntax of a Python lambda function

How to define a lambda function

Defining a lambda function is simple: use the lambda keyword, followed by the parameters, a colon, and a single expression.

lambda arguments: expression
Syntax of a lambda function

For example, a lambda function to square a number can be defined as:

square = lambda n: n * n
print(square(5))

Lambda functions differ from traditional functions because they don't have a name and are used inline for immediate execution.

Try changing the above code to get a better understanding. Modify the above function to handle different operations, such as subtraction or division, instead of multiplication.

Difference between lambda functions and def-defined functions

Lambda functions and traditional functions defined using the def keyword serve similar purposes but differ in structure, flexibility, and usage. Both can perform identical tasks, but each has its strengths depending on the scenario. Here's an example of how to reverse a string using both methods:

# Defining a function with `def`
def reverse_string(s):
return s[::-1]
# Defining a lambda function
lambda_reverse = lambda s: s[::-1]
# Output
my_string = "hello"
print("Using function defined with `def` keyword, reverse of "+ my_string + ":" + reverse_string(my_string))
print("Using lambda function, reverse of " + my_string + ":" + lambda_reverse(my_string))

Output

  • Using function defined with def keyword, reverse of 'hello': olleh

  • Using lambda function, reverse of 'hello': olleh

  • With def: The reverse_string() function is defined using the def keyword, which allows for better readability and the potential for more complex logic, should you need it.

  • With lambda: The lambda function is a one-liner, directly reversing the string. It’s concise and ideal for quick operations but not well-suited for more complex tasks or when readability is a priority.

Both achieve the same result, however, there are key differences between these two approaches:

Lambda function

def-defined function

Suitable for single-line expressions that return a value.

Supports multiple lines of code within the function block.

Ideal for short, inline operations or data manipulations.

Best for more complex tasks requiring multiple steps or logic.

Can reduce readability when used excessively.

Allows for comments and descriptions to enhance readability.

Cannot contain statements or expressions beyond a single line.

Can contain any number of lines, including complex logic.

Both approaches are valuable, and the choice between them depends on the complexity of the task at hand.

Try it yourself

Write a lambda function to handle cases where the input is zero or negative.

# Write your code here

After you try, you can refer to the given solution after pressing the "Run" button if you are stuck.

Why use lambda functions?

Lambda functions have several advantages:

  • Concise and readable: They eliminate the need for verbose function definitions when only a small operation is required.

  • Inline use: You can use lambdas inside other functions or pass them as arguments, making them ideal for quick operations.

  • Functional programming: Lambdas pair well with higher-order functions like map(), filter(), and reduce(), allowing for more expressive code.

When should you use a lambda function?

You should consider using lambda functions in the following scenarios:

  • Simple, one-off operations: When you need a small, quick function without the need to reuse it elsewhere.

  • Arguments for higher-order functions: Lambda functions are perfect when passed as arguments to functions that expect a function object, like map() or filter().

  • Cleaner and shorter code: When brevity improves readability, using a lambda function can make your code more concise.

Let's explore map() implementation with lambda:

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

Common use cases for lambda functions

Lambda functions are widely used in Python for tasks such as:

  • Mapping and transforming data: Apply a function to each item in an iterable.

  • Filtering data: Filter items from an iterable based on a condition.

  • Sorting data: Sort lists or dictionaries using a lambda function as the key.

  • Reducing sequences: Combine elements of a sequence to produce a single result.

Example 1: Using lambda with filter()

The filter() function selects items from a list based on a condition.

numbers = [1, 2, 3, 4, 5, 6]
even_numbers = list(filter(lambda x: x % 2 == 0, numbers))
print(even_numbers)

Example 2: Using lambda with reduce()

The reduce() function applies a rolling computation to a sequence of elements and returns a single value.

In the following example, we'll calculate the product of all numbers in a list using lambda and reduce().

from functools import reduce
# List of numbers
numbers = [1, 2, 3, 4, 5]
# Using reduce() with a lambda function to calculate the product of the list elements
product = reduce(lambda x, y: x * y, numbers)
# Using format() for string formatting instead of f-strings
print("The product of all numbers in {} is: {}".format(numbers, product))

In the above code:

  • Lambda function: lambda x, y: x * y takes two arguments, x and y, and returns their product.

  • reduce() function: It applies the lambda function to pairs of elements in the list, successively multiplying them together. For the list [1, 2, 3, 4, 5], the computation proceeds as ((1 * 2) * 3) * 4 * 5, resulting in 120.

This use of lambda with reduce() is perfect for performing operations on a list of values in a concise way, without the need to define a separate function.

Example 3: Sorting a list of tuples using lambda

Let's see how we can sort a list of tuples using Python lambda function:

pairs = [(2, 'two'), (1, 'one'), (3, 'three')]
sorted_pairs = sorted(pairs, key=lambda pair: pair[0])
print(sorted_pairs)

Try experimenting with the given executable code. Play around and observe how the output changes.

Pros and cons of a lambda function in Python

Let's have a look at some pros and cons of the lambda function in Python:

Pros

Cons

  • Compact and concise: Lambda functions allow you to write small functions in a single line.

  • Functional programming: Useful in functional programming paradigms, especially when working with higher-order functions.

  • Anonymous functions: Lambdas don't require a function name, making them ideal for one-time use.

  • Limited to one expression: Lambda functions can only handle a single expression, which may limit their use for complex logic.

  • Debugging issues: Since lambda functions don’t have a name, they can make debugging more challenging.

  • Readability: Overuse of lambdas in complex code can make your code harder to understand.

Quiz

Let’s quickly assess our understanding of Python lambda functions by trying the following quiz:

Test yourself!

1

What is the main characteristic of a Python lambda function?

A)

It is used for defining long, complex functions.

B)

It can have multiple expressions and return multiple values.

C)

It can have any number of parameters but only one expression.

D)

It is mandatory to use in all Python programs.

Question 1 of 30 attempted

Key takeaways

  • Lambda functions offer a quick and concise way to write anonymous functions for small tasks in Python.

  • They are ideal for use with higher-order functions like map(), filter(), and sorted().

  • Lambda functions can accept any number of parameters but are limited to a single expression, making them useful for simple operations.

  • For more complex functionality requiring loops or conditionals, use def functions instead of lambdas.

  • Pros include brevity and ease of use in functional programming, while cons include limited functionality and potential readability issues.

  • Use lambdas when a small, simple function is required, but avoid overusing them in complex scenarios for the sake of clarity.

Become a Data Analyst with our comprehensive learning path!

Unlock the power of data with our Become a Data Analyst path. Whether you’re a beginner or looking to transition into a data-driven career, this step-by-step journey will equip you with the skills to turn raw data into actionable insights.

From mastering SQL, Python, to learning data visualization and showcasing your analytical skills, this path has it all. Develop expertise in data cleaning, analysis, and storytelling to make informed decisions and drive business success. With hands-on practice, portfolio-building projects, and personalized guidance from our AI mentor, you’ll gain the confidence and knowledge to excel in interviews and secure your first job as a Data Analyst.

Start your data journey today!

Frequently asked questions

Haven’t found what you were looking for? Contact Us


What is the difference between a lambda function and a regular function in Python?

Lambda function: Defined using the lambda keyword, it can only contain a single expression and is usually written in one line. It is typically used for short-term, throwaway operations.

Regular function: Defined using the def keyword, it can contain multiple expressions and statements. It is used for more complex and reusable logic.


Can a lambda function have multiple expressions in Python?

No, lambda functions in Python can only have one expression. If you need to perform multiple operations, you should use a regular function defined with the def keyword.


Can lambda functions have default argument values in Python?

Yes, lambda functions can have default arguments just like regular functions. For example:

lambda x, y=10: x + y

This lambda function will add x and y, where y has a default value of 10.


Is it possible to assign a lambda function to a variable in Python?

Yes, you can assign a lambda function to a variable. For example:

add = lambda x, y: x + y
print(add(2, 3))  # Output: 5

This allows you to reuse the lambda function by calling it through the variable.


Are lambda functions faster than regular functions in Python?

Lambda functions are not necessarily faster than regular functions. Both are compiled to the same bytecode, so the speed difference is minimal. However, lambda functions are more concise and can make the code cleaner in cases where you need quick, small functions.


Can you use lambda functions with list comprehensions in Python?

Yes, lambda functions can be used in conjunction with list comprehensions or generator expressions. However, list comprehensions are often more readable and are preferred over lambda functions for creating lists in Python. See the example below:

squares = [lambda x: x*x for x in range(5)]
# Call each lambda function
for func in squares:
    print(func(2))  # Output: 4 for each call

What common mistakes should I avoid when using lambda functions?

Here are some typical errors learners might encounter:

  • Misusing lambda in complex situations: Avoid using lambda functions for complex logic. If your function requires multiple expressions or statements, it’s better to define a standard function using def.

  • Misunderstanding scope and limitations: Lambda functions are limited to a single expression and lack a name, which can lead to confusion when debugging. Always consider if a traditional function might be clearer and more maintainable.


Free Resources

Copyright ©2024 Educative, Inc. All rights reserved