{"id":25663,"date":"2021-12-04T09:18:55","date_gmt":"2021-12-04T03:48:55","guid":{"rendered":"https:\/\/python-programs.com\/?p=25663"},"modified":"2021-12-04T09:18:55","modified_gmt":"2021-12-04T03:48:55","slug":"python-itertools-product-function-with-examples","status":"publish","type":"post","link":"https:\/\/python-programs.com\/python-itertools-product-function-with-examples\/","title":{"rendered":"Python Itertools.product() Function with Examples"},"content":{"rendered":"

Itertools Module:<\/strong><\/p>\n

Itertools is a Python module that contains a collection of functions for dealing with iterators. They make it very simple to iterate through iterables such as lists and strings.<\/p>\n

Itertools in Python refers to a Python module that allows the creation of iterators, which aids in efficient looping, as well as time and space efficiency. itertools enable us to solve complex problems quickly and easily. Iterators are classified into three types.<\/p>\n

This module provides the following types of iterators:<\/p>\n

    \n
  1. Combinatorics Generators<\/li>\n
  2. Infinite Iterators<\/li>\n
  3. Terminating Iterators<\/li>\n<\/ol>\n

    itertools.product() Function:<\/strong><\/p>\n

    Cartesian Product of two sets is defined in mathematics as the set of all ordered pairs (a, b) where a belongs to A and b belongs to B.<\/p>\n

    itertools.product() belongs to the Python itertools library’s Combinatoric iterators category.<\/p>\n

    itertools.product() returns the cartesian product from the specified iterator, with the output being lexicographically sorted.<\/p>\n

    There are two ways to use itertools.product():<\/p>\n

    itertools.product(*iterables, repeat=1): <\/strong><\/p>\n

    This function returns the cartesian product of the provided iterable with itself for the number of times specified by the optional keyword “repeat.”<\/p>\n

    For example, product(arr, repeat=4) is equivalent to product (arr, arr, arr, arr).
    \nitertools.product(*iterables):<\/strong><\/p>\n

    This function returns the cartesian product of all iterables passed as arguments. For instance, product (arr1, arr2, arr3, arr4).<\/p>\n

    Consider the following example to gain a better idea.<\/p>\n

    Examples:<\/strong><\/p>\n

    Example1:<\/strong><\/p>\n

    Input:<\/strong><\/p>\n

    Given first List = [10, 9, 8]\r\nGiven second List = [12, 3, 40]<\/pre>\n

    Output:<\/strong><\/p>\n

    The cartesian product of the given two lists = \r\n[(10, 12), (10, 3), (10, 40), (9, 12), (9, 3), (9, 40), (8, 12), (8, 3), (8, 40)]<\/pre>\n

    Example2:<\/strong><\/p>\n

    Input:<\/strong><\/p>\n

    Given first List = [78, 2, 6]\r\nGiven second List = [4, 2, 7]<\/pre>\n

    Output:<\/strong><\/p>\n

    The cartesian product of the given two lists = \r\n[(78, 4), (78, 2), (78, 7), (2, 4), (2, 2), (2, 7), (6, 4), (6, 2), (6, 7)]<\/pre>\n

    Itertools.product() Function with Examples in Python<\/h2>\n