[Tutor] Difference between filter and map

Chris Calloway cbc at unc.edu
Tue Jan 23 16:40:21 CET 2007


vanam wrote:
> i want to know the difference between filter(function,sequence) and 
> map(function,sequence).

>>> print filter.__doc__
filter(function or None, sequence) -> list, tuple, or string

Return those items of sequence for which function(item) is true.  If
function is None, return the items that are true.  If sequence is a
tuple or string, return the same type, else return a list.
>>> print map.__doc__
map(function, sequence[, sequence, ...]) -> list

Return a list of the results of applying the function to the items of
the argument sequence(s).  If more than one sequence is given, the
function is called with an argument list consisting of the corresponding
item of each sequence, substituting None for missing values when not all
sequences have the same length.  If the function is None, return a list
of the items of the sequence (or a list of tuples if more than one
sequence).
>>>

filter returns a subsequence of a sequence based on passing each item in
the sequence to a function which returns a *boolean context*. If the
returns value's boolean context is true, the item is placed in the new
subsequence. map returns a sequence of the same length based on the
return value of passing each item in the sequence to a function.

One literally filters a sequence. The other literally maps a sequence.

filter can return a tuple, string, or list. map only returns a list.

I tried for a simple script with an function
> which finds the square of the number,after including separately filter 
> and map in the script i am getting the same results for instance
> def squ(x):
>      return x*x
> filter(squ,range(1,3))->1,4(output)
> map(squ,range(1,3)->1,4(output)

The boolean context of the return value of squ is true for all items of
the sequence which you passed it in filter. Also, the filter you showed
above does *not* return [1,4]. It returns [1,2], which is every item in
range(1,3), because every item in that list passes the filter function's
  boolean context (is x*x true?).

-- 
Sincerely,

Chris Calloway
http://www.seacoos.org
office: 332 Chapman Hall   phone: (919) 962-4323
mail: Campus Box #3300, UNC-CH, Chapel Hill, NC 27599




More information about the Tutor mailing list