[Tutor] Difference between filter and map
Kent Johnson
kent37 at tds.net
Tue Jan 23 16:10:41 CET 2007
vanam wrote:
> i want to know the difference between filter(function,sequence) and
> map(function,sequence).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)
Are you sure about that? I get
In [1]: def sq(x): return x*x
...:
In [2]: filter(sq, range(3))
Out[2]: [1, 2]
In [3]: map(sq, range(3))
Out[3]: [0, 1, 4]
map(fn, lst) returns a new list with fn applied to each element of lst.
In terms of list comprehensions, it is [ fn(x) for x in lst ].
filter(fn, lst) returns a new list containing all elements of the
original list for which fn(x) is true. As a list comprehension, it is
[ x for x in lst if fn(x) ]
Kent
More information about the Tutor
mailing list