How to use filter() and map()

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Ephexeve
    New Member
    • May 2011
    • 20

    How to use filter() and map()

    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
  • bvdet
    Recognized Expert Specialist
    • Oct 2006
    • 2851

    #2
    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:
    Code:
    >>> 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:
    Code:
    >>> 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)]

    Comment

    Working...