Open In App

itertools.combinations() Module in Python to Print All Possible Combinations

Last Updated : 28 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

When given an array of size n, one common problem is generating all possible combinations of r elements.

For example:

Input: arr[] = [1, 2, 3, 4], r = 2
Output: [(1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4)]

Although, there can be a recursive solution for this problem, but in this article we’ll focus on solving it using Python’s itertools.combinations().

What does itertools.combinations()

It returns r length subsequences of elements from the input iterable. Combinations are emitted in lexicographic sort order. So, if the input iterable is sorted, the combination tuples will be produced in sorted order.

  • itertools.combinations(iterable, r): It returns r-length tuples in sorted order with no repeated elements. For Example, combinations(‘ABCD’, 2) ==> [AB, AC, AD, BC, BD, CD].
  • itertools.combinations_with_replacement(iterable, r): It returns r-length tuples in sorted order with repeated elements. For Example, combinations_with_replacement(‘ABCD’, 2) ==> [AA, AB, AC, AD, BB, BC, BD, CC, CD, DD].

Let’s now implement a simple function that returns all combinations of size r from an array:

Python
from itertools import combinations

def rSubset(arr, r):
    return list(combinations(arr, r))

if __name__ == "__main__":
    arr = [1, 2, 3, 4]
    r = 2
    print(rSubset(arr, r))

Output
[(1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4)]

Explanation:

  • combinations(arr, r) generates an iterator of all possible r-length combinations.
  • list() is used to convert this iterator into a list of tuples for easy printing or further use.


Practice Tags :

Similar Reads