Fundamentals 6 min read

10 Common Uses of Lambda Functions in Python

Python's lambda (anonymous) functions, despite being limited to a single expression, can be employed in a variety of practical scenarios such as mapping, filtering, sorting, reducing, zipping, decorating, and implementing strategy patterns, as illustrated by ten concise code examples.

Test Development Learning Exchange
Test Development Learning Exchange
Test Development Learning Exchange
10 Common Uses of Lambda Functions in Python

Lambda functions in Python, also known as anonymous functions, are small one‑line functions that can be used in many practical contexts.

1. Using lambda with map() to apply a transformation to each element of a list.

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

2. Using lambda with filter() to select elements that satisfy a condition.

my_list = [1, 2, 3, 4, 5]
new_list = filter(lambda x: x%2 == 0, my_list)
print(list(new_list))  # Output: [2, 4]

3. Using lambda as the key function for list.sort() to sort a list of tuples by a specific element.

my_list = [(1, 3), (4, 1), (2, 8)]
my_list.sort(key=lambda x: x[1])
print(my_list)  # Output: [(4, 1), (1, 3), (2, 8)]

4. Using lambda with reduce() to aggregate a sequence into a single value.

from functools import reduce
my_list = [1, 2, 3, 4, 5]
result = reduce(lambda x, y: x + y, my_list)
print(result)  # Output: 15

5. Using lambda with map() to combine two lists element‑wise into tuples.

my_list = [1, 2, 3]
my_new_list = [4, 5, 6]
new_list = map(lambda x, y: (x, y), my_list, my_new_list)
print(list(new_list))  # Output: [(1, 4), (2, 5), (3, 6)]

6. Using a lambda that returns a tuple to sort by multiple keys with specified order.

my_list = [(1, 3), (4, 1), (2, 8)]
my_list.sort(key=lambda x: (x[1], x[0]))
print(my_list)  # Output: [(4, 1), (1, 3), (2, 8)]

7. Using a lambda inside a decorator to dynamically modify a function’s behavior.

def my_decorator(g):
    return lambda x: g(x) + 1

@my_decorator
def my_function(x):
    return x * 2

print(my_function(3))  # Output: 7

8. Using lambda with sorted() to order a list of objects by an attribute.

class Student:
    def __init__(self, name, grade):
        self.name = name
        self.grade = grade

student_list = [Student('Alice', 95), Student('Bob', 85), Student('Charlie', 75)]
sorted_list = sorted(student_list, key=lambda x: x.grade, reverse=True)
for student in sorted_list:
    print(student.name)  # Output: Alice, Bob, Charlie

9. Using lambda with map() to generate a dictionary where each key maps to its square.

my_dict = dict(map(lambda x: (x, x**2), range(1, 11)))
print(my_dict)  # Output: {1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81, 10: 100}

10. Using lambda functions to implement the strategy pattern, allowing the choice of algorithm at runtime.

def add(x, y):
    return x + y

def multiply(x, y):
    return x * y

def apply(func, x, y):
    return func(x, y)

print(apply(lambda x, y: x + y, 2, 3))  # Output: 5
print(apply(lambda x, y: x * y, 2, 3))  # Output: 6

In summary, lambda functions provide concise, flexible tools for mapping, filtering, sorting, reducing, combining sequences, decorating functions, and implementing design patterns, making Python code more compact and expressive.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

PythonLambdaTutorial
Test Development Learning Exchange
Written by

Test Development Learning Exchange

Test Development Learning Exchange

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.