How does FILTER and MAP works in Python | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

How does FILTER and MAP works in Python

How are those function/methods used,when to use them

12th Nov 2018, 10:34 AM
Leboman HKD Galis
Leboman HKD Galis - avatar
3 Answers
+ 13
filter & map is applied on lists , sets etc . filter is used to take out some certain elements which satisy a particular condition ,& map is used to apply transformation function on every element . //in very simple words , general meaning .
12th Nov 2018, 11:54 AM
Gaurav Agrawal
Gaurav Agrawal - avatar
+ 6
You use them when you want to apply a function over and over on different values and store them (map) or to apply a test on a list of values and only keep the values that get through the test (filter). Let me add an example. My function figures out if a number is a 'Howling Prime' (whatever that is). So if I call it once, I will get one result: True or False. By applying the function on a range of values, I can keep only these that check as True and them. https://code.sololearn.com/ckSkf5AE9B8T/?ref=app The * just means: Open the box with the results and take them out (in this case in order to print them one by one).
12th Nov 2018, 10:40 AM
HonFu
HonFu - avatar
+ 4
map functions expects a function object and any number of iterables like list, dictionary, etc. It executes the function_object for each element in the sequence and returns a list of the elements modified by the function object Here is an code which van help u understand better def multi(x): return x * 2 map(multi, [1, 2, 3, 4]) It can also reduce with the help of using lambda like this map(lambda x : x*2, [1, 2, 3, 4]) filter function expects two arguments, function_object and an iterable. function_object returns a boolean value. function_object is called for each element of the iterable and filter returns only those element for which the function_object returns true. For better understanding i want to give an simple example which help you a = [1, 2, 3, 4, 5, 6] filter(lambda x : x % 2 == 0, a) Because only element in list whose mod 2 is equal to 0 will print # Output: [2, 4, 6]
12th Nov 2018, 10:48 AM
MsJ
MsJ - avatar