{"id":25607,"date":"2021-11-23T08:54:12","date_gmt":"2021-11-23T03:24:12","guid":{"rendered":"https:\/\/python-programs.com\/?p=25607"},"modified":"2021-11-23T08:54:12","modified_gmt":"2021-11-23T03:24:12","slug":"python-itertools-combinations-function-with-examples","status":"publish","type":"post","link":"https:\/\/python-programs.com\/python-itertools-combinations-function-with-examples\/","title":{"rendered":"Python Itertools.combinations() 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.combinations() Function:<\/strong><\/p>\n

    Generate and print all possible combinations of r elements in an array of size n.<\/p>\n

    It returns r length subsequences of the input iterable’s elements. Combinations are emitted in alphabetical order. As a result, if the input iterable is sorted, the combination tuples will be generated in the same order.<\/p>\n

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

    itertools.combinations(iterable, r)<\/pre>\n

    Parameters<\/strong><\/p>\n

    iterable:<\/strong>\u00a0This is Required. Elements whose combinations must be performed out.<\/p>\n

    r:<\/strong>\u00a0This is Required. It is the length of the outputs.<\/p>\n

    Using itertools.combinations(iterable, r):<\/strong>
    \nIt returns sorted r-length tuples with no repeated elements.<\/p>\n

    for example:<\/p>\n

    combinations(‘ABCD’, 2) = [AB, AC, AD, BC, BD, CD].<\/p>\n

    Using combinations_with_replacement(iterable, r):<\/strong>
    \nIt returns sorted r-length tuples with repeated elements.<\/p>\n

    for example:<\/p>\n

    combinations_with_replacement(‘ABCD’, 2),\u00a0 = [AA, AB, AC, AD, BB, BC, BD, CC, CD, DD].<\/span><\/p>\n

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

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

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

    Given list\u00a0 = [5, 6, 7, 8]\r\nGiven r value =  2<\/pre>\n

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

    The possible combinations are : \r\n[(5, 6), (5, 7), (5, 8), (6, 7), (6, 8), (7, 8)]<\/pre>\n

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

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

    Given list\u00a0 = [10, 50, 100, 40]\r\nGiven r value =  3<\/pre>\n

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

    The possible combinations are : \r\n[(10, 50, 100), (10, 50, 40), (10, 100, 40), (50, 100, 40)]<\/pre>\n

    itertools.combinations() Function with Examples in Python<\/h2>\n