Lambda Functions

Next Topic(s):

Created:
2nd of October 2024
06:04:25 PM
Modified:
2nd of October 2024
07:30:35 PM

Exploring Lambda Functions in Python

Lambda functions are a special type of function in Python, commonly known as anonymous functions because they do not require a defined name. Unlike standard functions defined using the def keyword, lambda functions are defined using the lambda keyword, which makes them concise and often used for simple operations.

What Are Lambda Functions?

A lambda function is a small, one-line function defined without a name. It can have any number of arguments, but it can only have one expression. The result of this expression is implicitly returned. This makes lambda functions useful for tasks where a simple function is needed, without the overhead of defining a complete function using the def keyword.

How to Define Lambda Functions

Lambda functions are defined using the lambda keyword followed by the arguments and the expression. The basic syntax is:

        
# Syntax of a lambda function
lambda arguments: expression
        
        

Example: A simple lambda function that adds two numbers:

        
# Lambda function to add two numbers
add = lambda x, y: x + y
print(add(2, 3))  # Output: 5
        
        

Output:

    5
    

Explanation: The lambda function takes two arguments, x and y, and returns their sum. The add variable stores the lambda function, and calling add(2, 3) returns the result 5.

When Are Lambda Functions Useful?

Lambda functions are particularly useful when you need to define a short function for a limited scope. They are often used as arguments to higher-order functions, such as map(), filter(), and sorted(), which expect a function as an argument. Instead of defining a separate function using def, you can use a lambda function inline to make the code more concise and readable.

Common Use Cases for Lambda Functions

  • Sorting: Lambda functions are often used as the key argument in sorting functions to specify custom sorting criteria.
  • Mapping and Filtering: They are used with map() to transform data and with filter() to filter elements based on conditions.
  • Simple Mathematical Operations: Lambda functions are useful for defining quick mathematical calculations, such as addition, multiplication, or logical operations.

Example: Sorting a List of Tuples

Lambda functions are often used as the key argument to specify how to sort a list of tuples by a specific element.

        
# Sort a list of tuples by the second element
tuples_list = [(1, 3), (2, 1), (3, 2)]
sorted_list = sorted(tuples_list, key=lambda x: x[1])
print("Sorted List of Tuples:", sorted_list)
        
        

Output:

    Sorted List of Tuples: [(2, 1), (3, 2), (1, 3)]
    

Exercise Programs

Exercise 1: Multiply Each Element in a List by 2 Using Lambda and Map

Problem: Write a Python program that uses a lambda function with map() to multiply each element in a list by 2.

        
# Multiply each element by 2 using lambda and map
numbers = [1, 2, 3, 4, 5]
doubled_numbers = list(map(lambda x: x * 2, numbers))
print("Doubled Numbers:", doubled_numbers)
        
        

Exercise 2: Filter Even Numbers from a List Using Lambda and Filter

Problem: Write a Python program that uses a lambda function with filter() to filter out only the even numbers from a list.

        
# Filter even numbers using lambda and filter
numbers = [1, 2, 3, 4, 5, 6, 7, 8]
even_numbers = list(filter(lambda x: x % 2 == 0, numbers))
print("Even Numbers:", even_numbers)
        
        

Exercise 3: Create a List of Squares Using Lambda and Map

Problem: Write a Python program that uses a lambda function with map() to create a list of squares for numbers from 1 to 10.

        
# Create a list of squares using lambda and map
numbers = range(1, 11)
squares = list(map(lambda x: x ** 2, numbers))
print("List of Squares:", squares)
        
        

Solutions to the Exercises

Solution 1: Multiply Each Element in a List by 2

        
# Solution 1: Multiply each element by 2
numbers = [1, 2, 3, 4, 5]
doubled_numbers = list(map(lambda x: x * 2, numbers))
print("Doubled Numbers:", doubled_numbers)
        
        

Output:

    Doubled Numbers: [2, 4, 6, 8, 10]
    

Solution 2: Filter Even Numbers from a List

        
# Solution 2: Filter even numbers
numbers = [1, 2, 3, 4, 5, 6, 7, 8]
even_numbers = list(filter(lambda x: x % 2 == 0, numbers))
print("Even Numbers:", even_numbers)
        
        

Output:

    Even Numbers: [2, 4, 6, 8]
    

Solution 3: Create a List of Squares

        
# Solution 3: Create a list of squares
numbers = range(1, 11)
squares = list(map(lambda x: x ** 2, numbers))
print("List of Squares:", squares)
        
        

Output:

    List of Squares: [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
    
đŸ’¡

Interesting Fact: Lambda functions can only contain a single expression, which is implicitly returned. This makes them great for simple operations, but they cannot include complex logic or multiple statements like traditional functions defined with def.

Point to Take Care: Avoid using lambda functions when your logic is complex. In such cases, defining a regular function makes the code easier to understand and debug.