1

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

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.