Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (50.2k points)

 In python 2, the filter, map, and reduce work perfectly. Here is an example:

>>> def f(x):

        return x % 2 != 0 and x % 3 != 0

>>> filter(f, range(2, 25))

[5, 7, 11, 13, 17, 19, 23]

>>> def cube(x):

        return x*x*x

>>> map(cube, range(1, 11))

[1, 8, 27, 64, 125, 216, 343, 512, 729, 1000]

>>> def add(x,y):

        return x+y

>>> reduce(add, range(1, 11))

55

But when I am trying in Python 3, I receive the following outputs:

>>> filter(f, range(2, 25))

<filter object at 0x0000000002C14908>

>>> map(cube, range(1, 11))

<map object at 0x0000000002C82B70>

>>> reduce(add, range(1, 11))

Traceback (most recent call last):

  File "<pyshell#8>", line 1, in <module>

    reduce(add, range(1, 11))

NameError: name 'reduce' is not defined

1 Answer

0 votes
by (108k points)

Please be informed that the map() and filter() was purposely changed in newer version of Python so that it can return iterators, and reduce was eliminated from being a built-in and placed in functools.reduce.

You can use the below code:

>>> def f(x): return x % 2 != 0 and x % 3 != 0

...

>>> list(filter(f, range(2, 25)))

[5, 7, 11, 13, 17, 19, 23]

>>> def cube(x): return x*x*x

...

>>> list(map(cube, range(1, 11)))

[1, 8, 27, 64, 125, 216, 343, 512, 729, 1000]

>>> import functools

>>> def add(x,y): return x+y

...

>>> functools.reduce(add, range(1, 11))

55

>>>

The below code will replace your usage of map and filter with generators expressions or list comprehensions. Example:

>>> def f(x): return x % 2 != 0 and x % 3 != 0

...

>>> [i for i in range(2, 25) if f(i)]

[5, 7, 11, 13, 17, 19, 23]

>>> def cube(x): return x*x*x

...

>>> [cube(i) for i in range(1, 11)]

[1, 8, 27, 64, 125, 216, 343, 512, 729, 1000]

>>>

Browse Categories

...