Map, Filter, and Reduce

Map
The map function in Python is used to apply a function to all the elements of an iterable and returns a map object (another iterator).

Syntax
map(, , ...) You can pass multiple iterable arguments to the map function. The function will be applied to iterable elements passed.

Examples
WITHOUT using map : numbers = [4, 3, 6, 9, 11] squared = [] for number in numbers: squared.append(i**2) WITH using map : numbers = [4, 3, 6, 9, 11] squared = list(map(lambda x: x**2, numbers)) print(squared) [16, 9, 36, 81, 121] We usually use lambdas with map, but we can also use regular functions : def square(x): return x**2 numbers = [4, 3, 6, 9, 11] result = map(square, numbers) print(list(return)) [16, 9, 36, 81, 121]
 * 1) Returns:
 * 1) Returns:

Filter
The filter function creates a list of elements for which a function returns True. It tests each element in the iterable to be True of False.

Syntax
filter

Examples
The following code filters out the vowels in a given string : def vowels(letter): v = ['a', 'e', 'i', 'o', 'u'] if letter in v:        return True else: return False string = ['h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd'] filtered = filter(vowels, string) for each in filtered: print(each) e o o Like with the map function, it is more common to use a lambda function : string = ['h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd'] result = filter(lambda x: x.lower in ['a', 'e', 'i', 'o', 'u'], string) print(list(result)) ['e', 'o', 'o']
 * 1) Returns :
 * 1) Returns :

Reduce
This function is used for performing a particular function on  a list and returns the result.

Syntax
reduce

Examples
Lets say we wanted to compute the product of a list of integers. If we do this WITHOUT reduce : product = 1 numbers = [1, 2, 3, 4] for each in numbers: product = product * num If we do the same thing WITH reduce : from functools import reduce product = reduce((lambda x, y: x * y), numbers) Lets say we want to find the maximum number in a list of numbers : maximum = reduce(lambda x, y: x if x > y else y, numbers) print(maximum)
 * 1) product = 24
 * 1) product = 24