Map and Filter

 


Lambda Expressions, Map, and Filter

Now it's time to quickly learn about two built-in functions, filter, and map. Once we learn about how these operate, we can learn about the lambda expression, which will come in handy when you begin to develop your skills further!

map function

The map function allows you to "map" a function to an iterable object. That is to say, you can quickly call the same function to every item in an iterable, such as a list. For example:

def square(num):
    return num**2
my_nums = [1,2,3,4,5]
print(map(square,my_nums))

OUTPUT

<map 0x205baec21d0>


# To get the results, either iterate through map()
# or just cast to a list

print(list(map(square,my_nums)))

OUTPUT

[1, 4, 9, 16, 25]

The functions can also be more complex

def splicer(mystring):
    if len(mystring) % 2 == 0:
        return 'even'

Read Also

    else:
        return mystring[0]
mynames = ['John','Cindy','Sarah','Kelly','Mike']
print(list(map(splicer,mynames)))

OUTPUT

['even', 'C', 'S', 'K', 'even']

filter function

The filter function returns an iterator yielding those items of iterable for which function(item) is true. Meaning you need to filter by a function that returns either True or False. Then passing that into filter (along with your iterable) and you will get back only the results that would return True when passed to the function.

def check_even(num):
    return num % 2 == 0
nums = [0,1,2,3,4,5,6,7,8,9,10]
print(filter(check_even,nums))

OUTPUT

<filter at 0x205baed4710>


print(list(filter(check_even,nums)))

OUTPUT

[0, 2, 4, 6, 8, 10]

Post a Comment