Map, Filter, and Reduce

Question Click to View Answer

What does the following code print?

add_one = lambda x: x + 1
print(add_one(7))

8 is printed.

The variable add_one is assigned to an anonymous function. Anonymous functions don't have a name and are created with the lambda keyword.

What does the following code print?

multiply_by_two = lambda x: x * 2
numbers = [1, 2, 3]
doubled = map(multiply_by_two, numbers)
doubled_list = list(doubled)
print(doubled_list)

[2, 4, 6] is printed.

The multiply_by_two variable is assigned to an anonymous function.

The map() function takes an anonymous function and a list as arguments and returns a map object.

The map object is converted to a list and then printed.

What does the following code print?

letters = ["beach", "car"]
funified = list(map(lambda word: f"{word} is fun!", letters))
print(funified)

['beach is fun!', 'car is fun!'] is printed.

The map() function is used to iterate over every element in the letters array and append the " is fun!" string.

The map() function takes an anonymous function as the first argument and a list as the second argument.

What does the following code print?

nums = [3, 5, 16, 27]
some_nums = list(filter(lambda num: num < 10, nums))
print(some_nums)

[3, 5] is printed.

The filter() function is used to create an array that only includes the numbers less than 10.

filter() takes an anonymous function as the first argument and a list as the second argument.

What does the following code print?

words = ["bay", "cat", "boy", "fan"]
b_words = list(filter(lambda word: word.startswith("b"), words))
print(b_words)

['bay', 'boy'] is printed.

The filter() function takes an anonymous function as the first argument and a list of words as the second argument.

All the words that do not start with "b" are filtered from the list and the resulting list is printed.

What does the following code print?

nums = [4, 5, 6]
squares = list(map(lambda num: num ** 2, nums))
print(squares)

[16, 25, 36] is printed.

The map() function iterates through every number in the nums array and calculates the square of the number.

What does the following code print?

from functools import reduce
numbers = [1, 2, 3, 4]
sum = reduce(lambda x, y: x + y, numbers)
print(sum)

10 is printed.

The reduce() function iterates through every number in the numbers list and calculates the sum.

What does the following code print?

from functools import reduce
words = ["mary", "had", "a", "little", "lamb"]
biggest_word = reduce(lambda x, y: x if len(x) > len(y) else y, words)
print(biggest_word)

"little" is printed.

The reduce() function iterates through every word in the words list and keeps track of the biggest word. This is a handy way to find the biggest word in a list!