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!
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.
That being said, the iterators from itertools are often significantly faster than regular iteration from a standard Python for loop.
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.
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.
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()
.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With