How to use lambda in Python?

Home » Python » How to use lambda in Python?

Table of Contents

Introduction to lambda in Python

lambda in Python refers to an anonymous, small, and simple function that can have any number of arguments, but can only have a single expression.

The function is defined using the lambda keyword, and unlike regular functions defined with def, lambda functions don’t have a name (hence the term “anonymous”).

Syntax of lambda in Python

lambda arguments: expression
  • lambda: The keyword used to define an anonymous function.
  • arguments: The parameters that the lambda function takes (can be more than one).
  • expression: A single expression whose result will be returned by the lambda function.

Key Points About lambda in Python:

  1. Anonymous: Lambda functions do not have a name, unlike normal functions defined using def.
  2. Single Expression: Lambda functions can only contain a single expression. They are limited in functionality compared to regular functions, which can contain multiple statements.
  3. Return Value: Lambda functions automatically return the result of the expression without needing an explicit return statement.

Example of a Simple Lambda Function


# A simple lambda function that adds two numbers
add = lambda x, y: x + y

# Using the lambda function
result = add(5, 3)
print(result)  # Output: 8

In this example:

  • The lambda function lambda x, y: x + y takes two arguments x and y and returns their sum.
  • The result is then assigned to result and printed.

Use Cases of Lambda Functions

Lambda functions are useful when you need a small function for a short duration, and you don’t want to define a full function using def. They are commonly used in situations where the function is simple and will be used only once or twice.

Some common use cases of lambda functions include:

Sorting with Custom Keys: Lambda functions are frequently used to provide custom sorting behavior. For example, when sorting a list of tuples, you can specify which element to sort by using a lambda.


# Sorting a list of tuples based on the second element
items = [(1, 'apple'), (2, 'orange'), (3, 'banana')]
sorted_items = sorted(items, key=lambda x: x[1])
print(sorted_items)

In this example:

The lambda x: x[1] specifies that the sorting should be done based on the second element (x[1]) of each tuple.

Using Lambda with map(): The map() function applies a given function to each item in an iterable (like a list). Lambda functions are commonly used with map() to apply simple operations.


numbers = [1, 2, 3, 4]
squared_numbers = map(lambda x: x ** 2, numbers)
print(list(squared_numbers))  # Output: [1, 4, 9, 16]

In this example:

lambda x: x ** 2 defines a simple function that squares each number in the list.

Using Lambda with filter(): The filter() function is used to filter elements from an iterable based on a condition. You can use lambda functions to define this condition.


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

In this example:

lambda x: x % 2 == 0 is used to filter even numbers from the list.

Using Lambda with reduce() (from functools module): The reduce() function applies a binary function cumulatively to the items of an iterable, reducing the iterable to a single value. Lambda functions are often used in combination with reduce().


from functools import reduce

numbers = [1, 2, 3, 4]
product = reduce(lambda x, y: x * y, numbers)
print(product)  # Output: 24

In this example:

lambda x, y: x * y multiplies the elements of the list together.

Inline Functions: Lambda functions are also used for quick, one-time use cases where defining a function using def would be overkill.


# Adding a list of numbers inline using lambda
add_numbers = (lambda x, y: x + y)(10, 5)
print(add_numbers)  # Output: 15

Advantages of Lambda Functions

  1. Conciseness: Lambda functions are shorter and more concise than normal functions, especially when the function is simple.
  2. Ease of Use: They are handy when you need a function for a short duration or in functional programming contexts (like map()filter()reduce()).
  3. Readability: For small, simple operations, lambda functions can make code more readable by eliminating the need to define a separate function.

Disadvantages of Lambda Functions

  1. Limited Functionality: Lambda functions can only contain a single expression and can’t have statements (e.g., loops, conditionals) or multiple expressions.
  2. Reduced Clarity: While lambda functions are concise, they can sometimes reduce code clarity, especially when used in complex operations. This can make code harder to understand for someone unfamiliar with the lambda syntax.
  3. Debugging: Because lambda functions are anonymous, they are harder to debug, as they don’t have meaningful names.

Conclusion of lambda in Python

lambda function in Python is an anonymous, inline function that can take multiple arguments but only has one expression.

Use cases for lambda functions include sortingfiltering, and mapping data, as well as simplifying function definitions when the function is small and used temporarily.

While lambda functions are concise and useful, they are limited in functionality and can reduce clarity when overused in complex scenarios.


Posted

in

by

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *