Python Lambda Function

In this tutorial, you will learn about Lambda Function In Python

 

Introduction


In Python, a lambda function is a small anonymous function defined using the lambda keyword.

Lambda functions are also known as anonymous functions because they don't have a name.

They are useful for writing short, throw-away functions without the need to formally define a function using the def keyword.

Lambda functions are particularly handy in situations where a small function is needed for a short period and doesn't warrant a full function definition.

 

Syntax


The syntax for a lambda function is as follows:

lambda arguments: expression


lambda: Keyword indicating the start of the lambda function.

arguments: Comma-separated list of input parameters to the function.

expression: Single expression whose result is implicitly returned.

 

Basic Examples


Let's start with some basic examples to illustrate the syntax and usage of lambda functions.

Example 1: Square a Number

square = lambda x: x ** 2
print(square(5))  # Output: 25

In this example, the lambda function takes one argument x and returns its square.

Example 2: Add Two Numbers

add = lambda a, b: a + b
print(add(3, 7))  # Output: 10

This lambda function takes two arguments, a and b, and returns their sum.

 

Use Cases


Lambda functions are often employed in situations where a small function is required for a short duration. Some common use cases include:

1. Passing Functions as Arguments

Lambda functions are frequently used when a function needs to be passed as an argument to another function, such as with the map(), filter(), and sorted() functions.

numbers = [1, 4, 2, 7, 5]
squared_numbers = list(map(lambda x: x ** 2, numbers))
print(squared_numbers)  # Output: [1, 16, 4, 49, 25]

2. Sorting a List of Tuples

Lambda functions are handy when sorting a list of tuples based on a specific element.

students = [('Alice', 22), ('Bob', 19), ('Charlie', 25)]
sorted_students = sorted(students, key=lambda x: x[1])
print(sorted_students)
# Output: [('Bob', 19), ('Alice', 22), ('Charlie', 25)]

 

Limitations


While lambda functions are concise and useful in certain scenarios, they have some limitations:

Single Expression: Lambda functions can only contain a single expression.

Limited Functionality: Complex logic is better suited for regular functions defined with def.

Readability: Overuse of lambda functions in complex scenarios can lead to reduced code readability.

 

Summary


Lambda functions in Python provide a concise way to create small, anonymous functions. They are particularly useful in situations where a simple function is needed temporarily. However, it's important to use them judiciously, keeping in mind their limitations and the impact on code readability.
 

© 2022-2023 All rights reserved.