FANDOM


Map()Edit

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).

SyntaxEdit

map(<function to apply>, <iterable list of inputs>, ...)

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

ExamplesEdit

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)

# Returns:
[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))

# Returns:
[16, 9, 36, 81, 121]

Filter()Edit

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.

SyntaxEdit

filter(<function>, <iterable>)

ExamplesEdit

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)

# Returns :
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))

# Returns :
['e', 'o', 'o']

Reduce()Edit

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

SyntaxEdit

reduce(<function>, <list>)

ExamplesEdit

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

# product = 24

If we do the same thing WITH reduce() :

from functools import reduce


product = reduce((lambda x, y: x * y), numbers)

# product = 24

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)

ReferencesEdit

Python map() function

Map, Filter and Reduce

Python map() function

filter() in python reduce() in Python

Community content is available under CC-BY-SA unless otherwise noted.