Friday, 07 February 2025

Practical examples of lambda functions in Python

Python 

Lambda functions in Python are small, anonymous functions defined with the lambda keyword. They can have any number of arguments but only one expression. The expression is evaluated and returned when the lambda function is called. Lambda functions are often used for short, throwaway functions that are not needed later in the code.

Here are some detailed examples of lambda functions in Python:

Example 1: Basic Lambda Function

A simple lambda function that adds two numbers:

add = lambda x, y: x + y
print(add(5, 3))  # Output: 8

Example 2: Using Lambda with map()

The map() function applies a lambda function to each item in an iterable (e.g., a list):

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

Example 3: Using Lambda with filter()

The filter() function uses a lambda function to filter elements from an iterable:

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

Example 4: Using Lambda with sorted()

A lambda function can be used as the key argument in sorted() to customize sorting:

students = [
    {"name": "Alice", "age": 25},
    {"name": "Bob", "age": 22},
    {"name": "Charlie", "age": 30}
]
# Sort by age
sorted_students = sorted(students, key=lambda x: x["age"])
print(sorted_students)
# Output: [{'name': 'Bob', 'age': 22}, {'name': 'Alice', 'age': 25}, {'name': 'Charlie', 'age': 30}]

Example 5: Lambda with Multiple Arguments

A lambda function can take multiple arguments:

multiply = lambda x, y, z: x * y * z
print(multiply(2, 3, 4))  # Output: 24

Example 6: Lambda with Conditional Logic

You can include conditional logic in a lambda function:

max_value = lambda x, y: x if x > y else y
print(max_value(10, 20))  # Output: 20

Example 7: Lambda in a List Comprehension

Using a lambda function inside a list comprehension:

numbers = [1, 2, 3, 4, 5]
doubled = [(lambda x: x * 2)(x) for x in numbers]
print(doubled)  # Output: [2, 4, 6, 8, 10]

Example 8: Lambda with Default Arguments

Lambda functions can have default arguments:

greet = lambda name, greeting="Hello": f"{greeting}, {name}!"
print(greet("Alice"))  # Output: Hello, Alice!
print(greet("Bob", "Hi"))  # Output: Hi, Bob!

Example 9: Lambda with reduce()

The reduce() function from the functools module can use a lambda function to accumulate results:

from functools import reduce
numbers = [1, 2, 3, 4, 5]
product = reduce(lambda x, y: x * y, numbers)
print(product)  # Output: 120

Example 10: Lambda for Sorting Strings

Sorting a list of strings by their length using a lambda function:

fruits = ["apple", "banana", "cherry", "date"]
sorted_fruits = sorted(fruits, key=lambda x: len(x))
print(sorted_fruits)  # Output: ['date', 'apple', 'banana', 'cherry']

Example 11: Lambda with Nested Functions

Using a lambda function inside another function:

def multiplier(n):
    return lambda x: x * n

double = multiplier(2)
triple = multiplier(3)

print(double(5))  # Output: 10
print(triple(5))  # Output: 15

Example 12: Lambda with if-else in a Single Expression

A lambda function can include a ternary operator for conditional logic:

check_even = lambda x: "Even" if x % 2 == 0 else "Odd"
print(check_even(4))  # Output: Even
print(check_even(5))  # Output: Odd

Example 13: Lambda with No Arguments

A lambda function can also take no arguments:

greet = lambda: "Hello, World!"
print(greet())  # Output: Hello, World!

Example 14: Lambda with zip()

Using a lambda function with zip() to process multiple lists:

list1 = [1, 2, 3]
list2 = [10, 20, 30]
result = list(map(lambda x, y: x + y, list1, list2))
print(result)  # Output: [11, 22, 33]

Example 15: Lambda with pandas (Data Analysis)

Using a lambda function with pandas to apply a transformation to a DataFrame column:

import pandas as pd

data = {"Name": ["Alice", "Bob", "Charlie"], "Age": [25, 30, 35]}
df = pd.DataFrame(data)

# Add a new column with modified values
df["Age_plus_5"] = df["Age"].apply(lambda x: x + 5)
print(df)
# Output:
#       Name  Age  Age_plus_5
# 0    Alice   25          30
# 1      Bob   30          35
# 2  Charlie   35          40

Lambda functions are powerful for concise, inline operations but should be used judiciously. For complex logic, defining a regular function with def is often more readable.



Search