CodeBlanks Logo Icon CodeBlanks

combinations and permutations

Learn combinatorics with combinations and permutations.

combinations and permutations

combinations(iterable, r) produces the combinations (unordered) of length r from a set. permutations(iterable, r) produces the permutations (ordered). Both are in the itertools module.

Example: list(combinations([1, 2, 3], 2)) returns [(1, 2), (1, 3), (2, 3)]. list(permutations([1, 2, 3], 2)) returns [(1, 2), (1, 3), (2, 1), (2, 3), (3, 1), (3, 2)]. Use permutations if order matters, combinations otherwise.

When to use?

If you need an unordered selection from a list, use combinations. Example: choosing 2 people from a team. For ordered selection, use permutations. Example: choosing a president and a deputy.

Both return an iterator; you can see the results with list(). If r is not given, permutations tries all lengths; combinations requires r. Computational complexity grows quickly; use carefully on large data.

Practice Choose pairs with combinations

Start with from itertools import combinations. Generate all pair combinations with result = list(combinations([1, 2, 3], 2)). Then print with print(result).

Starter code

main.py
# Generate pair combinations

Sample solution

main.py
# Generate pair combinations
from itertools import combinations

result = list(combinations([1, 2, 3], 2))
print(result)

Expected output

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

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Match combinations and permutations

Term Meaning
combinations Unordered
permutations Ordered
(1, 2) Combination example
(2, 1) Permutation example

2 Which one for choosing president and deputy?

  • combinations
  • islice
  • chain
  • permutations Correct answer

Explanation: Permutations. Since order matters, permutations is used.

3 combinations import line

Question
from itertools import ____

result = list(combinations([1, 2, 3], 2))
print(result)
Answer
from itertools import combinations

result = list(combinations([1, 2, 3], 2))
print(result)

Explanation: combinations is in the itertools module.

All lessons in Intermediate