Reputation: 11
Hi this code works in python 2.7 but not in python 3
import itertools
def product(a,b):
return map(list, itertools.product(a, repeat=b)
print(sorted(product({0,1}, 3)))
it outputs
[[0, 0, 0], [0, 0, 1], [0, 1, 0], [0, 1, 1], [1, 0, 0], [1, 0, 1], [1, 1, 0], [1, 1, 1]]
in python 2.7 but in python 3 it gives map object at 0x028DB2F0 does anyone know how to change this to work for python 3 so the output remains the same as in python 2.7
Upvotes: 1
Views: 1607
Reputation: 43899
In Python 3, the map()
builtin returns an iterator rather than a list, behaving somewhat like the Python 2 itertools.imap()
function.
If you need a list, you can simply pass that iterator to list()
. For example:
>>> x = map(lambda x: x + 1, [1, 2, 3])
>>> x
<map object at 0x7f8571319b90>
>>> list(x)
[2, 3, 4]
Upvotes: 1
Reputation: 29103
Simply wrap it by a list this way:
import itertools
def product(a,b):
return list(map(list, itertools.product(a, repeat=b))
print(sorted(product({0,1}, 3)))
Find more Getting a map() to return a list in Python 3.x
In two words in Python 3 map
Return an iterator that applies function to every item of iterable, yielding the results.
While in python 2.7 it
Apply function to every item of iterable and return a list of the results.
Upvotes: 2