Open In App

Python program to apply itertools.product to elements of a list of lists

Itertools is a module that consists of the methods to apply various iteration based operations including combinations, permutations, etc., on the iterable components in Python. It has a set lightweight, memory-efficient and fast tools for performing iterator algebra.

Note: For more information, refer to Python Itertools



itertools.product()

It is used to perform cartesian product within a list or among lists. The nested loops cycle in a way that the rightmost element advancing on every iteration. This pattern creates a lexicographic ordering and thus if the input’s iterables are sorted, the product tuples are also in sorted order.

It takes iterables as the parameter. The below example shows a very simple representation of itertools.product() method. Here it is used as a creation of a cartesian product.



Example:




import itertools
  
  
def product(str1, str2):
      
    # returning the list containing 
    # cartesian product
    return [x for x in itertools.product(list(str1),
                                         list(str2))]
  
print(product("GfG", "GFG"))

Output:

[(‘G’, ‘G’), (‘G’, ‘F’), (‘G’, ‘G’), (‘f’, ‘G’), (‘f’, ‘F’), (‘f’, ‘G’), (‘G’, ‘G’), (‘G’, ‘F’), (‘G’, ‘G’)]

Operating on list of lists

To use itertools.product() method on list of lists, perform unpacking operation first. It can be done using two ways:


Article Tags :