Batu Lab NotesPractical developer guides

Generate ordered assignment options with permutations

By Batu ยท English technical notes

Also published in our Blogger archive.

itertools.permutations is appropriate when both selection and order matter. This example has three people and two ordered duties: lead and reviewer. A tuple such as ("Ari", "Bea") means Ari is lead and Bea is reviewer; reversing it is a different assignment. Calling permutations(people, 2) therefore produces six results, because there are three choices for the first duty and two remaining choices for the second.

The program materializes the iterator only because the input is deliberately tiny and it wants to inspect the complete result. The assertions check the count, uniqueness, and two boundary tuples for this known input. They do not establish that a larger scheduling policy is fair or complete. permutations treats positions as distinct even if input values compare equal, so repeated source values can yield repeated-looking tuples; deduplicate the input first if that is not wanted. It also has factorial-style growth, making it unsuitable to blindly materialize for large pools.

itertools.permutations is part of the Python standard library and no newer API is used here. The official documentation describes it as producing successive length-r permutations without repeated positions and gives the size relationship n! / (n-r)! when applicable. The output is deterministic because the input tuple has a fixed order.

AI-assistance disclosure: this article was drafted with AI assistance and should be adapted to the rules of the system that consumes its assignments.

Source: Python itertools.permutations documentation.

from itertools import permutations

people = ("Ari", "Bea", "Chen")
assignments = list(permutations(people, 2))

assert len(assignments) == 6
assert len(set(assignments)) == 6
assert assignments[0] == ("Ari", "Bea")
assert assignments[-1] == ("Chen", "Bea")

for lead, reviewer in assignments:
    print(f"lead={lead}, reviewer={reviewer}")
lead=Ari, reviewer=Bea
lead=Ari, reviewer=Chen
lead=Bea, reviewer=Ari
lead=Bea, reviewer=Chen
lead=Chen, reviewer=Ari
lead=Chen, reviewer=Bea