How to Generate Permutations of Length r in Python
Generate and print all r-length permutations of a list using Python's itertools.permutations.
Python code
11 linesfrom itertools import permutations
def show_permutations(items, r):
result = list(permutations(items, r))
for perm in result:
print(perm)
print(f"Total: {len(result)}")
if __name__ == "__main__":
data = ["A", "B", "C"]
show_permutations(data, 2)
Output
('A', 'B')
('A', 'C')
('B', 'A')
('B', 'C')
('C', 'A')
('C', 'B')
Total: 6
How it works
The itertools.permutations function returns an iterator that yields tuples of length r, containing all possible orderings of r elements from the input iterable. The total number of permutations is calculated using the formula n! / (n-r)!, where n is the length of the input. Converting the iterator to a list materializes all permutations, which is fine for small inputs but can be memory-heavy for larger lists. The loop prints each permutation tuple, and the final line shows the count using len().
Common mistakes
- Forgetting that permutations considers order, so ('A','B') and ('B','A') are different.
- Specifying an `r` larger than the length of the input, which returns an empty result.
- Materializing large permutations into a list when an iterator would suffice for memory efficiency.
Variations
- Use `itertools.permutations(data)` without the `r` argument to get all full-length permutations.
- Use `itertools.combinations` if order does not matter.
Real-world use cases
- Generating all possible routes for a traveling salesman problem with a fixed number of stops.
- Testing password cracker scripts by enumerating all possible sequences of a given length.
- Creating every possible scheduling order for a small set of tasks to brute-force optimize a timeline.
Sponsored
More from Algorithms & data structures
- Binary Search for Ship Capacity in Python medium
- Binary Search on Answer in Python: Koko Eating Bananas medium
- Bucket Numbers into Histogram Bin Counts in Python easy
- Container With Most Water: Two-Pointer Solution in Python medium
- Count Smaller Elements to the Right in Python easy
- Depth First Search Traversal Order in Python easy
Keep learning
Related tutorials and quizzes for this topic.