Python Program to Find All Permutations of a List
itertools.permutations() function to find all permutations of a list like this: from itertools import permutations; list(permutations(your_list)).Examples
How to Think About It
Algorithm
Code
from itertools import permutations items = [1, 2, 3] all_perms = list(permutations(items)) print(all_perms)
Dry Run
Let's trace the list [1, 2, 3] through the code to see how permutations are generated.
Input list
items = [1, 2, 3]
Generate permutations
permutations(items) creates an iterator over all orderings of [1, 2, 3]
Convert to list
list(permutations(items)) collects all permutations into a list
Print result
Prints all 6 permutations as tuples
| Permutation |
|---|
| (1, 2, 3) |
| (1, 3, 2) |
| (2, 1, 3) |
| (2, 3, 1) |
| (3, 1, 2) |
| (3, 2, 1) |
Why This Works
Step 1: Using itertools.permutations
The permutations() function from itertools generates all possible orderings of the input list elements.
Step 2: Collecting permutations
We convert the iterator returned by permutations() into a list to see all permutations at once.
Step 3: Output format
Each permutation is a tuple showing one unique arrangement of the original list elements.
Alternative Approaches
def permute(lst): if len(lst) == 0: return [[]] result = [] for i in range(len(lst)): rest = lst[:i] + lst[i+1:] for p in permute(rest): result.append([lst[i]] + p) return result print(permute([1, 2, 3]))
def backtrack(start, lst, result): if start == len(lst): result.append(lst[:]) return for i in range(start, len(lst)): lst[start], lst[i] = lst[i], lst[start] backtrack(start + 1, lst, result) lst[start], lst[i] = lst[i], lst[start] result = [] backtrack(0, [1, 2, 3], result) print(result)
Complexity: O(n!) time, O(n!) space
Time Complexity
Generating all permutations requires factorial time because there are n! possible orderings for a list of length n.
Space Complexity
Storing all permutations also takes factorial space since each permutation is stored in the output list.
Which Approach is Fastest?
Using itertools.permutations() is fastest and simplest; recursive or backtracking methods are educational but slower and more complex.
| Approach | Time | Space | Best For |
|---|---|---|---|
| itertools.permutations | O(n!) | O(n!) | Fast, simple, built-in |
| Recursive approach | O(n!) | O(n!) | Learning recursion, manual control |
| Backtracking | O(n!) | O(n!) | Understanding in-place swaps |
itertools.permutations() for a simple and fast way to get all permutations.