Lambda map, reduce, and filter functions

Share Your Love

In this article, we are going to discuss the Lambda map, reduce, and filter built-in functions’ usage.

In Python, the map(), reduce(), and filter() functions are higher-order functions that can be used with lambda functions to perform various operations on lists and other iterable objects.

  1. map() function:

The map() the function applies a given function to each item of an iterable and returns a new iterable with the transformed values. The syntax for the map() function is:

map(function, iterable)

Here, function is the function to be applied to each item of the iterable, and iterable is the iterable object to be transformed.

You can use lambda functions with the map() function to apply a simple operation to each item of an iterable. For example, to square each item in a list, you can use the following code:

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

The reduce() the function applies a given function to the first two items of an iterable, then applies the function to the result and the next item, and so on, until all items have been processed. The syntax for the reduce() function is:

reduce(function, iterable)

Here, function is the function to be applied to the first two items of the iterable and their result, and iterable is the iterable object to be processed.

You can use lambda functions with the reduce() function to apply a simple operation to an iterable. For example, to find the product of all items in a list, you can use the following code:

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

The filter() the function applies a given function to each item of an iterable and returns a new iterable with only the items for which the function returns True. The syntax for the filter() function is:

filter(function, iterable)

Here, function is the function to be applied to each item of the iterable, and iterable is the iterable object to be filtered.

You can use lambda functions with the filter() function to filter an iterable based on a simple condition. For example, to filter out all even numbers from a list, you can use the following code:

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

Share Your Love
Avatar photo
Lingaraj Senapati

Hey There! I am Lingaraj Senapati, the Founder of lingarajtechhub.com My skills are Freelance, Web Developer & Designer, Corporate Trainer, Digital Marketer & Youtuber.

Articles: 411

Newsletter Updates

Enter your email address below to subscribe to our newsletter