0

Where to use Map and Filter i am confused :-

L = [i for i in range(0,11)] x = map(lambda a : True if (a%2 == 0) else False, L) new = [] #output = [True, False, True, False, True, False, True, False, True, False, True] for i in x: new.append(i) print(new) #and x = filter(lambda a : True if (a%2 == 0) else False, L) new = [] #output = [0,2,4,6,8,10] for i in x: new.append(i) print(new) https://code.sololearn.com/cy91Ks86A9A3/?ref=app

19th Feb 2019, 7:19 AM
Abhay
Abhay - avatar
6 Respostas
+ 1
You gave two examples of how to use them yourself. Can you explain what you really want to know? You use map when you want to use a function or method on every element of an iterable. print(*map(float, [1, 2, 3, 4, 5])) Output: 1.0 2.0 3.0 4.0 5.0 Every number gets turned into a float. You use filter when you only want to keep elements of an iterable that fulfill a condition, determined by a function returning True or False. print(*filter(str.isdigit, 'solo123learn456')) Output: 123456 (The * just 'unpacks' the map or filter object for printing the elements.)
19th Feb 2019, 7:49 AM
HonFu
HonFu - avatar
+ 1
I have edited my post, please read it. Does that clarify it a bit?
19th Feb 2019, 7:59 AM
HonFu
HonFu - avatar
+ 1
Simply map convertes all element in a list to another value after doing some functional expressions. In your example it maps all of the integers in the list (list for generated with a sequence from 0 to 10 using range method) to the boolean value True if they are divisible by 2. otherwise it will map those indivisible value to False. And in the second example it filters - or it returns all the elements in the list which match the given condition. In this case all the values divisible by 2 are filtered out from the function. Filter method is just like a filter that you use in your day to day life
19th Feb 2019, 9:02 AM
Seniru
Seniru - avatar
0
HonFu I know working but confused where to use them.
19th Feb 2019, 7:57 AM
Abhay
Abhay - avatar
0
HonFu please tell me
19th Feb 2019, 7:58 AM
Abhay
Abhay - avatar
12th Sep 2021, 10:08 PM
Nabeer Chowdhury
Nabeer Chowdhury - avatar