Open In App

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

Last Updated : 27 Feb, 2020
Comments
Improve
Suggest changes
Like Article
Like
Report
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: Python3 1==
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:
  • By unpacking the list inside function The example below shows that how can unpacking be performed by simple operation within the method. Python3 1==
    import itertools
    
    
    def product(list_of_str):
        
        str1 = list_of_str[0]
        str2 = list_of_str[1]
        
        # 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')]
    The disadvantage of this way is that, it requires additional information to be known i.e the length of the list inside the lists.
  • Using '*' operator To overcome the above mentioned disadvantage '*' is used to unpack the lists within the list. So the above code can be optimized as follows: Python3 1==
    import itertools
    
    
    def product(lst):
        
        # Unpack operation performed
        # by '*' operator and returning
        # the list containing cartesian
        # product
        return [x for x in itertools.product(*lst)]
    
    
    # list of lists being passed in the method
    print(product(["GfG", "GFG"]))
    
    Output
    [('G', 'G'), ('G', 'F'), ('G', 'G'), ('f', 'G'), ('f', 'F'), ('f', 'G'), ('G', 'G'), ('G', 'F'), ('G', 'G')]

Next Article
Practice Tags :

Similar Reads