Python Tutorial (11) Lambda Function

Lambda function in Python

What is a Lambda in python with Example?

In Python, a lambda function is a concise way to create small anonymous functions. Lambda functions can have any number of input parameters, but they can only have one expression. They are often used for short-term operations where a full function definition would be overkill. Here’s an example:

Example 1: Basic Lambda Function

# Regular function

def add(x, y):

    return x + y

# Equivalent lambda function

add_lambda = lambda x, y: x + y

# Using both functions

result_function = add(5, 3)

result_lambda = add_lambda(5, 3)

print(result_function)  # Output: 8

print(result_lambda)    # Output: 8

In this example, add_lambda is a lambda function that takes two parameters (x and y) and returns their sum. It is equivalent to the regular function add.

Example 2: Using Lambda with map()

# Using lambda with map to square each element in a list

numbers = [1, 2, 3, 4, 5]

squared_numbers = list(map(lambda x: x**2, numbers))

print(squared_numbers)  # Output: [1, 4, 9, 16, 25]

Here, the lambda function is used with the map() function to square each element in the numbers list.

Example 3: Using Lambda with filter()

# Using lambda with filter to keep even numbers in a list

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

even_numbers = list(filter(lambda x: x % 2 == 0, numbers))

print(even_numbers)  # Output: [2, 4, 6, 8, 10]

In this example, the lambda function is used with the filter() function to keep only the even numbers in the numbers list.

Example 4: Using Lambda with sorted()

# Using lambda with sorted to sort a list of tuples by the second element

pairs = [(1, 5), (3, 2), (7, 1), (4, 8)]

sorted_pairs = sorted(pairs, key=lambda x: x[1])

print(sorted_pairs)  # Output: [(7, 1), (3, 2), (1, 5), (4, 8)]

Here, the lambda function is used as the key argument in the sorted() function to sort a list of tuples by their second elements.

Example 5: Using Lambda in List Comprehension

# Using lambda in a list comprehension to create a list of squares

numbers = [1, 2, 3, 4, 5]

squares = [(lambda x: x**2)(num) for num in numbers]

print(squares)  # Output: [1, 4, 9, 16, 25]

Lambda functions can be used directly within list comprehensions to perform operations on each element of a list.

Lambda functions are particularly useful in situations where you need a small, throwaway function for a short-lived operation. They are commonly used with higher-order functions like map(), filter(), and sorted(). However, it’s essential to note that lambda functions are limited in complexity compared to regular named functions, so they are best suited for simple, one-line expressions.

Why we need use Lambda in Python with Example

Lambda functions in Python are useful for several reasons, particularly in scenarios where a small, anonymous function is needed for a short-lived operation. Here are some reasons why and examples of how lambda functions can be beneficial:

Conciseness and Readability:

Example:

# Using a regular function

def add(x, y):

    return x + y

# Using a lambda function

add_lambda = lambda x, y: x + y

Explanation:

Lambda functions are concise and can be defined in a single line. In situations where a simple operation is required, using a lambda function can lead to cleaner and more readable code.

Anonymous Functions for Short-Term Use:

Example:

# Using lambda with map to square each element in a list

numbers = [1, 2, 3, 4, 5]

squared_numbers = list(map(lambda x: x**2, numbers))

Explanation:

Lambda functions are often used for short-term operations within functions like map(), filter(), and sorted(). They provide a quick and concise way to define simple operations without the need for a full function definition.

Functional Programming Constructs:

Example:

# Using lambda with sorted to sort a list of tuples by the second element

pairs = [(1, 5), (3, 2), (7, 1), (4, 8)]

sorted_pairs = sorted(pairs, key=lambda x: x[1])

Explanation:

Lambda functions are commonly used in functional programming constructs, such as sorting and filtering, where a simple function is required to determine the order or selection criteria.

Inline Function Definitions:

Example:

# Using lambda in a list comprehension to create a list of squares

numbers = [1, 2, 3, 4, 5]

squares = [(lambda x: x**2)(num) for num in numbers]

Explanation:

Lambda functions can be used directly within list comprehensions, providing a concise way to apply an operation to each element of a list.

Callback Functions:

Example:

# Using lambda as a callback function in the sort method

students = [(“Alice”, 25), (“Bob”, 20), (“Charlie”, 22)]

sorted_students = sorted(students, key=lambda student: student[1])

Explanation:

Lambda functions are commonly used as callback functions in situations where a function is needed as an argument to another function, such as the key parameter in the sorted() function.

Functional Programming with Higher-Order Functions:

Example:

# Using lambda with filter to keep even numbers in a list

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

even_numbers = list(filter(lambda x: x % 2 == 0, numbers))

Explanation:

Lambda functions are often used in conjunction with higher-order functions like filter() to create more concise and expressive code for operations on iterable objects.

While lambda functions are powerful in specific situations, it’s essential to use them judiciously. For more complex operations or functions that will be reused, a regular named function with a full definition may be more appropriate. Lambda functions shine in situations where brevity and simplicity are key considerations.

Where we use Lambda in Python with Examples

Lambda functions in Python are used in situations where a small, anonymous function is required for a short-term operation.

They are particularly useful when you need a quick, one-line function and don’t want to define a full function using the def keyword. Here are some common use cases for lambda functions with examples:

Mapping and Transforming Data:

Example:

# Using lambda with map to square each element in a list

numbers = [1, 2, 3, 4, 5]

squared_numbers = list(map(lambda x: x**2, numbers))

print(squared_numbers)  # Output: [1, 4, 9, 16, 25]

Explanation:

Lambda functions are often used with the map() function to apply a transformation to each element in an iterable.

Filtering Data:

Example:

# Using lambda with filter to keep even numbers in a list

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

even_numbers = list(filter(lambda x: x % 2 == 0, numbers))

print(even_numbers)  # Output: [2, 4, 6, 8, 10]

Explanation:

Lambda functions are commonly used with the filter() function to selectively include elements in a list based on a condition.

Sorting Data:

Example:

# Using lambda with sorted to sort a list of tuples by the second element

pairs = [(1, 5), (3, 2), (7, 1), (4, 8)]

sorted_pairs = sorted(pairs, key=lambda x: x[1])

print(sorted_pairs)  # Output: [(7, 1), (3, 2), (1, 5), (4, 8)]

Explanation:

Lambda functions are frequently used as the key argument in the sorted() function to define a custom sorting criterion.

Callback Functions:

Example:

# Using lambda as a callback function in the sort method

students = [(“Alice”, 25), (“Bob”, 20), (“Charlie”, 22)]

sorted_students = sorted(students, key=lambda student: student[1])

print(sorted_students)

# Using lambda as a callback function in the sort method

students = [(“Alice”, 25), (“Bob”, 20), (“Charlie”, 22)]

sorted_students = sorted(students, key=lambda student: student[1])

print(sorted_students)

Explanation:

Lambda functions are commonly used as callback functions, such as when sorting or filtering based on a specific attribute.

Inline Functions in List Comprehensions:

Example:

# Using lambda in a list comprehension to create a list of squares

numbers = [1, 2, 3, 4, 5]

squares = [(lambda x: x**2)(num) for num in numbers]

print(squares)  # Output: [1, 4, 9, 16, 25]

Explanation:

Lambda functions can be used directly within list comprehensions for concise inline operations.

Simple Operations in GUIs and GUI Frameworks:

Example:

# Using lambda in a GUI framework (e.g., Tkinter)

from tkinter import Button, Tk

root = Tk()

button = Button(root, text=”Click me”, command=lambda: print(“Button clicked”))

button.pack()

root.mainloop()

Explanation:

Lambda functions are convenient for specifying simple operations in GUI frameworks as callback functions for buttons, events, etc.

While lambda functions are handy in specific contexts, they are not suitable for complex operations or functions that need to be reused across multiple parts of your code.

In such cases, it’s better to define a full function using the def keyword. Lambda functions are most effective for short-term, one-off operations where brevity is a priority.

Leave a Reply