Python Lambda Functions

A lambda function is a small anonymous function defined using the lambda keyword. It can take any number of arguments but can only have one expression. Lambda functions are often used for short, simple functions.

Example 1: Simple Lambda Function

Create a lambda function that adds 10 to a number.

# Simple lambda function
add_ten = lambda x: x + 10
result = add_ten(5)
print("Result:", result)

Result: 15

Example 2: Lambda Function with Multiple Arguments

Calculate the sum of three numbers using a lambda function.

# Lambda with multiple arguments
sum_three = lambda a, b, c: a + b + c
result = sum_three(5, 10, 15)
print("Sum:", result)

Sum: 30

Example 3: Using Lambda with map() Function

Convert a list of temperatures from Celsius to Fahrenheit.

# Using lambda with map()
celsius = [0, 20, 35, 100]
fahrenheit = list(map(lambda x: (x * 9/5) + 32, celsius))
print("Fahrenheit:", fahrenheit)

Fahrenheit: [32.0, 68.0, 95.0, 212.0]

Example 4: Using Lambda with filter() Function

Filter out even numbers from a list of numbers.

# Using lambda with filter()
numbers = [1, 2, 3, 4, 5, 6]
even_numbers = list(filter(lambda x: x % 2 == 0, numbers))
print("Even Numbers:", even_numbers)

Even Numbers: [2, 4, 6]

Example 5: Using Lambda with sorted() Function

Sort a list of tuples based on the second element.

# Using lambda with sorted()
students = [
    ("Karthick AG", 85),
    ("Vijay", 92),
    ("John", 78),
    ("Durai", 88)
]
sorted_students = sorted(students, key=lambda x: x[1])
print("Sorted Students:", sorted_students)

Sorted Students: [('John', 78), ('Karthick AG', 85), ('Durai', 88), ('Vijay', 92)]

Example 6: Lambda Function in Dictionary

Use lambda functions as dictionary values.

# Lambda functions in a dictionary
operations = {
    'add': lambda x, y: x + y,
    'subtract': lambda x, y: x - y,
    'multiply': lambda x, y: x * y,
    'divide': lambda x, y: x / y
}
result = operations['multiply'](5, 3)
print("Result:", result)

Result: 15

Explanation: Lambda functions are useful for short, anonymous functions that are not reused elsewhere. They are often used with functions like map(), filter(), and sorted().