Generate all permutation of a set in Python
Last Updated :
29 May, 2025
Generating all permutations of a set in Python involves creating every possible ordered arrangement of its elements. Since sets are unordered collections, the first step is usually converting the set to a list to maintain a consistent order. For example, given the set {1, 2, 3}, the permutations include (1, 2, 3), (1, 3, 2), (2, 1, 3), and so on. Let’s explore different efficient methods to generate these permutations.
This is the most efficient way to generate permutations in Python using the standard library. itertools.permutations returns all possible orderings as tuples of the elements in an iterable.
Python
from itertools import permutations
s = {1, 2, 3}
a = list(s)
for p in permutations(a):
print(p)
Output(1, 2, 3)
(1, 3, 2)
(2, 1, 3)
(2, 3, 1)
(3, 1, 2)
(3, 2, 1)
Explanation: We convert the set {1, 2, 3} to a list to maintain a consistent order. Then, using itertools.permutations, we generate all unique arrangements of the list elements. Each permutation is returned as a tuple, which we print directly with no need for manual recursion or swapping.
Using heap
Heap's Algorithm is an efficient recursive algorithm for generating all permutations of n objects. It minimizes memory usage by performing swaps in-place and is useful when you want to generate permutations without creating new arrays.
Python
def fun(a, size):
if size == 1:
print(tuple(a))
return
for i in range(size):
fun(a, size - 1)
if size % 2 == 1:
a[0], a[size-1] = a[size-1], a[0]
else:
a[i], a[size-1] = a[size-1], a[i]
s = {1, 2, 3}
a = list(s)
fun(a, len(a))
Output(1, 2, 3)
(2, 1, 3)
(3, 1, 2)
(1, 3, 2)
(2, 3, 1)
(3, 2, 1)
Explanation: This function uses Heap’s algorithm, recursively reducing size to 1 to print permutations, swapping elements after each call based on size parity to generate all unique permutations.
Using backtracking recursive method
This method follows a classic recursive backtracking approach: pick an element, generate all permutations of the remaining elements and combine them. It's intuitive and great for learning how recursion works in permutation problems.
Python
def permute(arr):
if len(arr) == 0:
return []
if len(arr) == 1:
return [arr]
res = []
for i in range(len(arr)):
elem = arr[i]
rem = arr[:i] + arr[i+1:]
for p in permute(rem):
res.append([elem] + p)
return res
s = {1, 2, 3}
for p in permute(list(s)):
print(tuple(p))
Output(1, 2, 3)
(1, 3, 2)
(2, 1, 3)
(2, 3, 1)
(3, 1, 2)
(3, 2, 1)
Explanation: permute() fun generates all permutations by returning the list itself if it has one element or is empty. For longer lists, it selects each element, recursively permutes the rest, prefixes each with the selected element and gathers all results.
Related Articles