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.

Easy Python 3.9+ Aug 9, 2026 Comprehensions & generators 14 views 0 copies

Python code

16 lines
Python 3.9+
from 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

stdout
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

  1. Use `itertools.combinations` if order does not matter.
  2. 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

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Comprehensions & generators

Related tutorials and quizzes for this topic.