How do you generate all permutations of a list using recursion?
Pick each element in turn as the first element of the permutation, and recursively generate the permutations of the remaining elements. The base case is a list of zero or one element, which has exactly one permutation, itself.
def permutations(values):
if len(values) <= 1:
return [list(values)]
result = []
for index, value in enumerate(values):
rest = values[:index] + values[index + 1:]
for tail in permutations(rest):
result.append([value] + tail)
return result
print(permutations([1, 2, 3]))The output is six orderings: 1, 2, 3 then 1, 3, 2 then 2, 1, 3 then 2, 3, 1 then 3, 1, 2 then 3, 2, 1.
The mechanism is that a permutation is uniquely determined by its first element and a permutation of the rest. Because the base case has exactly one answer, and every larger list delegates to strictly smaller lists, the recursion is well founded and returns every ordering exactly once, with no duplicates and nothing missed.
The trade-off to name is factorial growth. Three elements give six permutations, ten elements give more than three million, and fifteen elements give more than a trillion, so the output size becomes the binding constraint long before the CPU does. There are two consequences worth stating. First, materialising the whole list of permutations is impossible for anything but a small input, so a generator that yields one at a time is the right shape. Second, the slicing on every level copies the list, so the time is not simply factorial but factorial times n, and a version that swaps elements in place avoids the copying.