Day 21: Map() , Filter() , Reduce() and Lambda Function in Python

Day 21: Map() , Filter() , Reduce() and Lambda Function in Python

Functional programming is a programming prototype that emphasizes the use of functions that take inputs and produce outputs without altering the state of the program. Python supports functional programming features such as lambda functions, map, filter, and reduce functions, which allow for a more declarative and expressive style of coding.

Lambda functions, also known as anonymous functions, are small, inline functions defined using the lambda keyword. They are useful for writing short, one-line functions without explicitly defining a function using def. Lambda functions can take any number of arguments but can only have a single expression.

lambda arguments: expression

arguments: input parameters or variables that the lambda function takes.
expression: Single expression or operation to be evaluated and returned as the result of the lambda function.

The map() function in Python is a built-in function that applies a specified function to each item of an iterable and returns a new iterable containing the results. It allows you to transform each element of the original iterable according to the provided function.

map(function, iterable)

Let's see an example where we use lambda functions with the map() function to manipulate a list of strings by converting each string to uppercase.

animals = ["dog", "cat", "panda", "tiger"]

#using map() with lambda function to convert each name to uppercase
uppercase_animals = list(map(lambda x: x.upper(), animals))

print("Original names:", animals)
print("Uppercase animal names:", uppercase_animals)
#output: Original names: ['dog', 'cat', 'panda', 'tiger']
# Uppercase animal names: ['DOG', 'CAT', 'PANDA', 'TIGER']
  • We use the map() function with a lambda function lambda x: x.upper() to convert each animal name to uppercase.

  • The lambda function takes one argument x (each animal name in the list) and returns its uppercase version using the upper() method.

  • The map() function applies this lambda function to each element of the list and returns an iterator of the results.

Lambda functions combined with higher-order functions like map() provide a powerful way to perform operations on iterable objects in Python while keeping the code concise and readable.

The filter() function in Python is used to filter elements from an iterable based on a specified condition. It takes two arguments: a function that defines the condition, and an iterable to be filtered.

filter(function, iterable)

Suppose you want to remove empty values (" ") from the list using the filter() function with a lambda function. Here's how it will happen:

animals = ["panda", " ", "tiger", "wolf", " "]

#removinf empty strings using filter() and lambda function
filtered_list = list(filter(lambda x: x != " ", animals))

print(filtered_list) #outpu: ['panda', 'tiger', 'wolf']
  1. We use the filter() function to remove the empty strings from the list. The filter() function takes two arguments: a function (or lambda function) that defines the condition, and the iterable.

  2. Within the filter() function, we specify a lambda function lambda x: x != " ". This lambda function takes a single argument x (each element in the list) and returns True if the element is not an empty string (" "), and False otherwise. This lambda function acts as the filtering condition.

  3. The filter() function iterates over each element of the list and applies the lambda function to each element. It retains elements for which the lambda function returns True (i.e., elements that are not empty strings) and discards elements for which the lambda function returns False.

The reduce() function in Python is a part of the functools module. It applies a specified function to the elements of an iterable cumulatively to reduce it to a single value. The reduce() function continuously applies the specified function to pairs of elements from the iterable until it is reduced to a single value.

from functools import reduce
output = reduce(function, iterable, initial)

using the reduce() function to find the maximum element in a list:

from functools import reduce
num = [10, 30, 5, 40, 20]

#using reduce() to find the maximum element
max_num = reduce(lambda x, y: x if x > y else y, num)

print("Maximum number:", max_num) #output: Maximum number: 40
  • The lambda function lambda x, y: x if x > y else y takes two arguments x and y (two consecutive elements of the list) and returns the greater of the two.

  • The reduce() function applies this lambda function cumulatively to the elements of the list until it is reduced to a single value, which is the maximum element.

  • The final maximum number is stored in the variable max_num and printed as output.

Subscribe to our newsletter

Read articles from directly inside your inbox. Subscribe to the newsletter, and don't miss out.

 

Article Series

Python