Skip to content

Instantly share code, notes, and snippets.

@innat
Last active November 24, 2018 15:50
Show Gist options
  • Save innat/51347f00c575c4a319c5522d4ef5bb11 to your computer and use it in GitHub Desktop.
Save innat/51347f00c575c4a319c5522d4ef5bb11 to your computer and use it in GitHub Desktop.
Python: Difference between filter(function, sequence) and map(function, sequence)

map and filter function in python is pretty different because they perform very differently. Let's have a quick example to differentiate them.

map function

Let's define a function which will take a string argument and check whether it presents in vowel letter sequences.

def lit(word):
    return word in 'aeiou'

Now let's create a map function for this and pass some random string.

for item in map(lit,['a','b','e']):
    print(item)

And yes it's equivalent to following

lit('a') , lit('b') , lit('e')

simply it will print

True
False
True 

filter function

Now let's create a filter function for this and pass some random string.

for item in filter(lit,['a','b','e']):
    print(item)

filter as the name implies, filters the original iterable and retents the items that return True for the function provided to the filter function.

Simply it will print

a
e
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment