[Tutor] Difference between filter and map

Alan Gauld alan.gauld at btinternet.com
Wed Jan 24 12:03:03 CET 2007

"vanam" <vgvr620034 at gmail.com> wrote

> Yes i did a mistake in expressing my problem below are the instances 
> of the
> script and its corresponding output,for each instance its giving 
> contrasting
> result i want explanation for that
> [1]:def squ(n):
>           return n*n

>     filter(squ,range(3))---->output is not seen on the interpreter
>     map(squ,range(3))----->output  not seen on the interpreter

I don;t know why you aren't seeing the output, I would expect
more or less the same output as the next two lines.
What tool are you using? Is it IDLE or something else?

> print filter(squ,range(3))----->output is [1,2]
> print map(squ,range(3))------>output is [0,1,4]

The first one returns the actual items from the list where
squ(item) evaluates to Ture,  ie non zero. The first item (0)
squared is zero so it is not included - it is filtered out, leaving
1 and 2 as the only output.

The second one returns the result of passing each item
through squ()each item. So you get 0,1,4 which are the
squares of 0,1,2

> [2]:def squ(n):
>          y = n*n
>          print y

This function prrints the values then returns None (Python's
default return value) which is equivalent to False in a boolean

>      filter(squ,range(3))-->Below is the output
>      0
>      1
>      4

filter applies squ to each item. squ prints the square.
filter then returns an empty list since squ always returns
None, which is false, so all items are filtered out.
Why it is not printed by the interpreter I don't know.

>      map(squ,range(3))-->Below is the output
>      0
>      1
>      4

As above but this time map returns a list of 3 Nones.
Why it is not printed I don't know.

>      print filter(squ,range(3))--->Below is the output
>      0
>      1
>      4
>      []
>      print map(squ,range(3))-->Below is the output
>      0
>      1
>      4
>      [None,None,None]

Exactly as above except the output from the functions is
actually being printed.

> I want to know why in each case its giving different results and 
> diff
> between filter and map

Hopefully my explanation has made that clear.
Why the versions without print do not display the result of the
functions is a mystery.


Alan Gauld
Author of the Learn to Program web site

More information about the Tutor mailing list