Lambda

Map

The map function applies a given function to each item of an iterable (e.g., a list) and returns a new iterable with the results.

# Double each number in a list
numbers = [1, 2, 3, 4]
doubled = map(lambda x: x * 2, numbers)
print(list(doubled))  # Output: [2, 4, 6, 8]

Filter

The filter function filters out elements from an iterable based on a condition (a function that returns True or False).

# Filter even numbers from a list
numbers = [1, 2, 3, 4, 5]
evens = filter(lambda x: x % 2 == 0, numbers)
print(list(evens))  # Output: [2, 4]

Reduce

The reduce function applies a function cumulatively to the items of an iterable, reducing it to a single value. It’s part of the functools module.

from functools import reduce

# Find the product of all numbers in a list
numbers = [1, 2, 3, 4]
product = reduce(lambda x, y: x * y, numbers)
print(product)  # Output: 24

Final Takeaway

  • Lambda functions are small, anonymous functions defined with lambda. They’re great for short, one-line operations.

  • map transforms each item in an iterable.

  • filter selects items from an iterable based on a condition.

  • reduce combines all items in an iterable into a single result.

Updated on