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. The method takes an optional argument called repeat
, which when used returns the cartesian product of the iterable with itself for the number of times specified in the repeat
parameter.
Let’s refer to the coding example below to understand more.
itertools.product(*iterables, repeat=1)
*iterables
: The list of iterables.repeat
: An integer argument that returns the cartesian product of the iterable with itself for the number of times specified.from itertools import productlst = [1,2,3,4,5]print("Original list - ", lst)print("Cartesian product of the list with itself - ", list(product(lst, repeat=2)))lst1 = [1, 2, 3]lst2 = ['a', 'b', 'c']print("Cartesian product of the lst1 and lst2 - ", list(product(lst1, lst2)))
product
function from itertools
module.lst
.lst
.product
function with lst
and repeat=2
as arguments to obtain the cartesian product of lst
with itself.lst11
.lst2
.product
function with lst1
and lst2
as arguments to obtain the cartesian product between lst1
and lst2
.