[Tutor] Difference between filter and map

Kent Johnson kent37 at tds.net
Tue Jan 23 16:38:58 CET 2007


vanam wrote:
> ya i am sure about that i am using python editor which has python 
> intrepreter attached to it i got the same output for both filter and map
> def squ(n):
>    y = n*n
>   print y
> filter(y,range(3))->0  1 4
> map(y,range(3))->0 1 4

This is quite different that what you posted the first time. This 
function squ() *prints* n*n but *returns* None (since it has no explicit 
return statement). The previous squ() actually returned n*n. But the 
results are still different if you look carefully:

In [2]: def sq(n):
    ...:     y=n*n
    ...:     print y
    ...:
    ...:

In [3]: map(sq, range(3))
0
1
4
Out[3]: [None, None, None]

The function sq() is called for each element of range(3) and prints the 
square. This is why 0, 1, 4 are printed. But the value returned from 
map() is the list [None, None, None] which is the accumulated return 
values from calling sq().

In [4]: filter(sq, range(3))
0
1
4
Out[4]: []

Here, sq() is still called for each element of range(3). Since the 
printing is from sq(), 0, 1 and 4 are still printed. But the return 
value is an empty list [] because None is not true so sq(n) is not true 
for any elements of range(3).

Kent



More information about the Tutor mailing list