Map and Filter are paradigms of functional programming. They allow you to apply a function across a number of iterables. map() and filter() functions are built-in with Python, so require no importing.

Map

It applies function to every item of iterable. Syntax of map() is

map(function, iterable, …)

It return an iterator that applies function to every item of iterable, yielding the results. If additional iterable arguments are passed, function must take that many arguments and is applied to the items from all iterables in parallel. With multiple iterables, the iterator stops when the shortest iterable is exhausted.

Below example demonstrate the use of map() function. Pet names are converted to upper case using for loop. Using map same goal is achieved using one line of code.

pets = ['rabbit', 'dog', 'cat']
uppered_pets = []

# 1. Change case to upper case using for loop
for pet in pets:
    pet_ = pet.upper()
    uppered_pets.append(pet_)

print(uppered_pets)

# Output
# ['RABBIT', 'DOG', 'CAT']

# 2. Change case to upper case using map
uppered_pets = list(map(str.upper, pets))
print(uppered_pets)

# Output
# ['RABBIT', 'DOG', 'CAT']

def squareFunc(x):
    return x**2

nums = (1, 8, 4, 5, 13, 26, 381, 410, 58, 47)

# 3. Calculate square using map
squares = list(map(squareFunc, nums))
print(squares)

# Output
# [1, 64, 16, 25, 169, 676, 145161, 168100, 3364, 2209]

Multiple iterator can also be used in map(). So, if the function passed to map requires two arguments, then you need to pass in two iterables to it. In the following example, each element in circle_areas is rounded up to certain decimal places. First element in the list to one decimal place, the second element in the list to two decimal places, and so on.

circle_areas = [3.56773, 5.57866, 4.987614, 56.234424, 9.145344]

result = list(map(round, circle_areas, range(0,5)))

print(result)

# Output
# [4.0, 5.6, 4.99, 56.234, 9.1453]

If the length of circle_areas and the length of range(1,3) differ, it will iterate over the elements until one of iterable has no next element.

Filter

It creates a list of elements for which a function returns true. Syntax of filter() function is:

filter(function, iterable)

Returns an iterator from those elements of iterable for which function returns true. iterable may be either a sequence, a container which supports iteration, or an iterator.

Below example creates list by filtering out the scores. It filter out student whose score is less than or equal to 70.

scores = [66, 90, 68, 59, 76, 60, 88, 74, 81, 65]

def score_70(score):
    return score > 70

over_75 = list(filter(score_70, scores))

print(over_75)

# Output
# [90, 76, 88, 74, 81]