Permutation and Combination in Python
Last Updated :
09 May, 2025
Python provides built-in methods to work with permutations and combinations using the itertools module. These are helpful in problems involving arrangement (order matters) and selection (order doesn’t matter) of elements.
Let's explore them one by one:
Permutation
A permutation is an arrangement of elements where the order matters. For example, (1, 2) and (2, 1) are two different permutations.
Python offers the permutations() method in the itertools module to generate these.
Example 1: Get All Permutations of a List
Python
from itertools import permutations
perm = permutations([1, 2, 3])
for i in perm:
print(i)
Output(1, 2, 3)
(1, 3, 2)
(2, 1, 3)
(2, 3, 1)
(3, 1, 2)
(3, 2, 1)
Explanation: permutations([1, 2, 3]) returns all possible orderings (3! = 6 permutations).
Example 2: Permutations of Specific Length
We can also generate permutations of a specific length r.
Python
from itertools import permutations
perm = permutations([1, 2, 3], 2)
for i in perm:
print(i)
Output(1, 2)
(1, 3)
(2, 1)
(2, 3)
(3, 1)
(3, 2)
Explanation: permutations([1, 2, 3], 2) returns 2-length ordered arrangements (nPr = 6).
Combination
A combination is a way to select elements where the order does not matter. For example, (1, 2) and (2, 1) are considered the same combination.
Python offers the combinations() method for this purpose.
Example 1: Get All Combinations of Length 2
Python
from itertools import combinations
comb = combinations([1, 2, 3], 2)
for i in comb:
print(i)
Output(1, 2)
(1, 3)
(2, 3)
Explanation:
- combinations([1, 2, 3], 2) returns all 2-element subsets without regard to order.
- Duplicates are avoided (e.g., (2,1) is not separate from (1,2)).
Example 2: Combinations from an Unsorted List
Python
from itertools import combinations
comb = combinations([2, 1, 3], 2)
for i in comb:
print(i)
Output(2, 1)
(2, 3)
(1, 3)
Explanation:
- combinations([2, 1, 3], 2) preserves the input order in output combinations.
- Elements are treated uniquely based on their position in the list.
Example 5: Combinations with Repetition
Use combinations_with_replacement() to allow repeated elements in combinations.
Python
from itertools import combinations_with_replacement
comb = combinations_with_replacement([1, 2, 3], 2)
for i in comb:
print(i)
Output(1, 1)
(1, 2)
(1, 3)
(2, 2)
(2, 3)
(3, 3)
Explanation: combinations_with_replacement([1, 2, 3], 2) includes combinations like (1, 1), allowing repetition.
Related articles: