By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
440,551 Members | 1,127 Online
Bytes IT Community
+ Ask a Question
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
Share this Question
Share on Google+
1 Reply


bvdet
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
  1. >>> map(lambda x: x**0.5, (1,2,3,4,5,6,7,8,9,10))
  2. [1.0, 1.4142135623730951, 1.7320508075688772, 2.0, 2.2360679774997898, 2.4494897427831779, 2.6457513110645907, 2.8284271247461903, 3.0, 3.1622776601683791]
  3. >>> map(lambda x, y: x**y, (1,2,3), (2,3,4))
  4. [1, 8, 81]
  5. >>> map(None, (1,2,3), (2,3,4))
  6. [(1, 2), (2, 3), (3, 4)]
  7. >>> map(str, (1,2,3))
  8. ['1', '2', '3']
  9. >>> 
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
  1. >>> filter(lambda x: isinstance(x, str), [1,2,3,4,'a','b',5,'c'])
  2. ['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

Post your reply

Sign in to post your reply or Sign up for a free account.