Course contentsShow
← Python
Lesson 184 of 1,0603. Functions and ModularizationFree lesson

Applying Lambda Functions to Data Collections

Learners will integrate lambda expressions within sorting keys and filtering logic to manipulate data structures efficiently and concisely.

In this lesson, you will learn how to leverage lambda expressions to perform concise sorting and filtering operations on data structures like lists and dictionaries.

Why Use Lambdas with Collections?

When working with collections of complex objects—such as a list of dictionaries or tuples—standard functions like sorted() or filter() often need a "hint" to know exactly which part of the data they should evaluate. While you could write a full def function for this, a lambda expression allows you to define that logic right where it is needed.

Sorting with Lambda Keys

The sorted() function accepts a key argument, which expects a function that transforms each element before comparison. Instead of defining a formal function, a lambda lets you grab a specific index or key on the fly.

Imagine you have a list of products, and you want to sort them by price:

products = [("Laptop", 1200), ("Mouse", 25), ("Monitor", 300)]

# Sort by the second element (the price) in each tuple
sorted_products = sorted(products, key=lambda item: item[1])

print(sorted_products)
# Output: [('Mouse', 25), ('Monitor', 300), ('Laptop', 1200)]

Filtering with Lambda Logic

The filter() function uses a predicate—a function that returns True or False—to decide which items to keep. A lambda is the perfect tool for these simple conditional checks.

numbers = [10, 5, 8, 20, 3]

# Keep only numbers greater than 8
filtered_nums = list(filter(lambda x: x > 8, numbers))

print(filtered_nums)
# Output: [10, 20]

Keep it Concise

When using lambdas with collections, remember the goal is readability. Because lambdas are anonymous and defined in a single line, they are best suited for simple expressions. If your logic grows to require multiple lines, complex conditional branches, or needs to be reused elsewhere, go back to using a standard def function to keep your code maintainable and clear.

Key Takeaway: Lambda expressions provide a lightweight way to provide custom sorting criteria or filtering conditions to collection-processing functions without the overhead of formal function definitions.