Skip to content
thesarfo

Note

map() and filter()

Generating a new list from an existing one using map and filter, and how they differ in what they return.

views 0

The map and filter functions are used to generate a list, from an already existing list.

Lets say you want to filter this list by a specific coffee, assuming you want to filter it by coffees that start with the letter C. You can use the output as a map and or a filter

menu = ["espresso", "mocha", "latte", "cappucino", "cortado", "americano"]

The map function takes two arguments, the first one is a function. In this case, it will be the function that will be used to map values based on the condition. The second argument is the variable that contains the arguments that will be passed through the function. In this case, it will be the coffees from the menu list

def find_coffee(coffee):
''' returns the items that start with c'''
if coffee[0] == 'c':
return coffee
map_coffee = map(find_coffee, menu)
print(map_coffee) # this gives you a map object
for x in map_coffee:
# loop through the map object,
# and print the ones that start with c
print(x)

The below code demonstrates how you can do the same thing, but with a filter function. The filter function works in the same way as a map function.

filter_coffee = filter(find_coffee, menu)
print(filter_coffee)
for x in filter_coffee:
print(x)

The above code outputs just the coffees that start with c, and leaves out the None in its output.