How to Generate Permutations of Length r in Python
Generate all ordered arrangements of length r from a given list of elements using itertools.permutations.
Python code
16 linesfrom itertools import permutations
def generate_permutations(elements, r):
"""Generate all r-length permutations of the given elements."""
return list(permutations(elements, r))
if __name__ == "__main__":
elements = ['A', 'B', 'C']
r = 2
result = generate_permutations(elements, r)
print(f"Elements: {elements}")
print(f"Length r: {r}")
print("Permutations:")
for perm in result:
print(perm)
print(f"Total: {len(result)}")
Output
Elements: ['A', 'B', 'C']
Length r: 2
Permutations:
('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 the input elements. When r is not specified, it defaults to the length of the iterable, producing full permutations. The list() call consumes the iterator into a list for easy inspection and reuse. Each permutation is a tuple that preserves the order of selection, making this ideal for problems where sequence matters.
Common mistakes
- Forgetting that permutations consider order: ('A','B') is different from ('B','A'), unlike combinations.
- Using a large `r` with a big input list can produce a huge number of results (n! / (n-r)!), leading to memory issues.
- Passing a generator as the first argument to `permutations` works, but be aware it will be consumed once.
- Not converting the iterator to a list when you need to access the permutations multiple times.
Variations
- Use `itertools.combinations` if order does not matter.
- Generate permutations lazily with a loop: `for p in permutations(elements, r):` to avoid memory bloat.
Real-world use cases
- Generating all possible ordering schedules for a small set of tasks to find an optimal sequence.
- Enumerating candidate passwords of fixed length during a security audit or brute-force test.
- Creating all possible arrangements of n items for testing combinatorial logic in unit tests.
Sponsored
More from Comprehensions & generators
- Batch Rows in Chunks with a Generator in Python easy
- Build a Generator Pipeline in Python: Filter Then Map medium
- Build a lazy generator to read file lines in Python easy
- Chunk an Iterable into Batches with a Generator in Python easy
- Convert Data in Python with Comprehensions and Generators easy
- Count Data in Python with Comprehensions and Generators easy
Keep learning
Related tutorials and quizzes for this topic.