How to Generate Permutations of Length r in Python

Generate and print all r-length permutations of a list using Python's itertools.permutations.

Easy Python 3.9+ Aug 9, 2026 Algorithms & data structures 15 views 0 copies

Python code

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

stdout
('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

  1. Use `itertools.permutations(data)` without the `r` argument to get all full-length permutations.
  2. 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

Run this sample

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

Open editor

More from Algorithms & data structures

Related tutorials and quizzes for this topic.