ragingcorgi
ragingcorgi

Reputation: 3468

itertools.product() return value

When I tried running the following code

product([1,2,3],['a','b'])

it returned an object of the following type:

<itertools.product object at 0x01E76D78>

Then I tried calling list() on it and I got the following:

[(1, 'a'), (1, 'b'), (2, 'a'), (2, 'b'), (3, 'a'), (3, 'b')]

Is there any way to make it into a list of lists, instead of tuples? Like this:

[[1, 'a'], [1, 'b'], [2, 'a'], [2, 'b'], [3, 'a'], [3, 'b']]

Thanks in advance!

Upvotes: 9

Views: 13048

Answers (3)

user541686
user541686

Reputation: 210352

list(map(list, product([1, 2, 3], ['a', 'b'])))

The outermost list() is not necessary on Python 2, though it is for Python 3. That is because in Python 3 a map object is returned by map().

Upvotes: 9

jamylak
jamylak

Reputation: 133504

You can do the following but it is pointless. Since the values do not change a tuple is more suited to this than a list. It also saves memory.

>>> from itertools import product
>>> [list(x) for x in product([1,2,3],['a','b'])]
[[1, 'a'], [1, 'b'], [2, 'a'], [2, 'b'], [3, 'a'], [3, 'b']]

Upvotes: 1

BrenBarn
BrenBarn

Reputation: 251355

It returns an iterator of tuples. If you want a list of lists, you can do:

[list(a) for a in product([1,2,3],['a','b'])]

However, in many cases, just using the iterator is better. You can just do:

for item in product([1,2,3],['a','b']):
    # do what you want with the item

Upvotes: 2

Related Questions