440,551 Members | 1,127 Online
Need help? Post your question and get tips & solutions from a community of 440,551 IT Pros & Developers. It's quick & easy.

# How to use filter() and map()

 P: 20 I am using Python 3.1.2, and I am having difficults understanding how the map() and filter() works, could anybody give me any help? what do they really do? Thanks in advance May 13 '11 #1
 Expert Mod 2.5K+ P: 2,851 Built-in function map() applies a function to each element of the list arguments. The number of list arguments must match the required number of function arguments. Examples: Expand|Select|Wrap|Line Numbers >>> map(lambda x: x**0.5, (1,2,3,4,5,6,7,8,9,10)) [1.0, 1.4142135623730951, 1.7320508075688772, 2.0, 2.2360679774997898, 2.4494897427831779, 2.6457513110645907, 2.8284271247461903, 3.0, 3.1622776601683791] >>> map(lambda x, y: x**y, (1,2,3), (2,3,4)) [1, 8, 81] >>> map(None, (1,2,3), (2,3,4)) [(1, 2), (2, 3), (3, 4)] >>> map(str, (1,2,3)) ['1', '2', '3'] >>>  Built-in function filter() constructs a list from the elements of argument list for which argument function returns True. Example: Expand|Select|Wrap|Line Numbers >>> filter(lambda x: isinstance(x, str), [1,2,3,4,'a','b',5,'c']) ['a', 'b', 'c'] Note the above is equivalent to: ` [x for x in [1,2,3,4,'a','b',5,'c'] if isinstance(x, str)]` May 13 '11 #2