Python itertools.combinations() Function



The Python itertools.combinations() function is used to generate all possible unique combinations of elements from a given iterable. Unlike permutations, the order of elements in a combination does not matter.

This function is useful in combinatorial problems where selecting subsets is required, such as lottery number selection, team formations, and probability calculations.

Syntax

Following is the syntax of the Python itertools.combinations() function −

itertools.combinations(iterable, r)

Parameters

This function accepts the following parameters −

  • iterable: The input iterable whose elements will be combined.
  • r: The length of each combination.

Return Value

This function returns an iterator that produces tuples representing all possible unique combinations.

Example 1

Following is an example of the Python itertools.combinations() function. Here, we generate all unique pairs from a list of numbers −

import itertools

numbers = [1, 2, 3]

result = itertools.combinations(numbers, 2)
for item in result:
   print(item)

Following is the output of the above code −

(1, 2)
(1, 3)
(2, 3)

Example 2

Here, we specify a combination length of 3, generating unique triplets from the given set −

import itertools

letters = ['A', 'B', 'C', 'D']

result = itertools.combinations(letters, 3)
for item in result:
   print(item)

Output of the above code is as follows −

('A', 'B', 'C')
('A', 'B', 'D')
('A', 'C', 'D')
('B', 'C', 'D')

Example 3

Now, we use itertools.combinations() function to generate all possible 2-letter combinations from a string −

import itertools

word = "XYZ"

result = itertools.combinations(word, 2)
for item in result:
   print(''.join(item))

The result obtained is as shown below −

XY
XZ
YZ

Example 4

When working with teams or group selections, itertools.combinations() function can help generate all possible team formations −

import itertools

players = ['Alice', 'Bob', 'Charlie', 'David']

result = itertools.combinations(players, 2)
for team in result:
   print(team)

The result produced is as follows −

('Alice', 'Bob')
('Alice', 'Charlie')
('Alice', 'David')
('Bob', 'Charlie')
('Bob', 'David')
('Charlie', 'David')
python_modules.htm
Advertisements