combinations and permutations
- Python course
- Intermediate
- Lesson 97/116
- 5 min
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
# Generate pair combinationsSample solution
# 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
from itertools import ____
result = list(combinations([1, 2, 3], 2))
print(result)
from itertools import combinations
result = list(combinations([1, 2, 3], 2))
print(result)
Explanation: combinations is in the itertools module.