Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 686
turtlesoup Avatar asked Jun 19 '12 06:06

turtlesoup


People also ask

What is Product () in Python?

In Python, itertools is a module in Python that provides functions. These functions help in iterating through iterables. The product() method of the itertools module returns the cartesian product of the input iterables.

Is Itertools product faster than for loops?

That being said, the iterators from itertools are often significantly faster than regular iteration from a standard Python for loop.

Is Itertools product efficient?

Itertools will make your code stand out. Above all, it will make it more pythonic. One would question the need for itertools. They are faster and much more memory efficient.

How do you use Cartesian product in Python?

Practical Data Science using Python As we know if two lists are like (a, b) and (c, d) then the Cartesian product will be {(a, c), (a, d), (b, c), (b, d)}. To do this we shall use itertools library and use the product() function present in this library. The returned value of this function is an iterator.


2 Answers

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().

like image 139
user541686 Avatar answered Oct 18 '22 00:10

user541686


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
like image 30
BrenBarn Avatar answered Oct 18 '22 02:10

BrenBarn