# Generate all permutation of a set in Python?

Arranging all the members of a set into some order or sequence and if the set is already ordered, rearranging (reordering) its elements is called permutation.

Generate all permutations using for loop

We will generate permutations using for loop −

## Example

def permutFunc(myList):

# No permutations for empty list
if len(myList) == 0:
return []

# Single permutation for only one element
if len(myList) == 1:
return [myList]

# Permutations for more than 1 characters
k = []

# Looping
for i in range(len(myList)):
m = myList[i]
res = myList[:i] + myList[i+1:]
for p in permutFunc(res):
k.append([m] + p)
return k

# Driver program
myList = list('456')
for p in permutFunc(myList):
print (p)


## Output

['4', '5', '6']
['4', '6', '5']
['5', '4', '6']
['5', '6', '4']
['6', '4', '5']
['6', '5', '4']


Generate all permutations using permutations() function

We will generate permutations using the permutations() function −

## Example

from itertools import permutations

# Using the permutations() method
myList = list(permutations(range(1, 3)))

# Display the Permutations
print("Permutations\n",myList)


## Output

Permutations
[(1, 2), (2, 1)]


Generate all permutations using permutations() in extend() function

To generate all permutations using the extend() function −

## Example

import itertools

myList = [2,3,4]

resList = []

for i in range(1,len(myList)+1):
resList.extend(list(itertools.permutations(myList, r=i)))

# Display the Permutations
print("Permutations\n",resList)


## Output

Permutations
[(2,), (3,), (4,), (2, 3), (2, 4), (3, 2), (3, 4), (4, 2), (4, 3), (2, 3, 4), (2, 4, 3), (3, 2, 4), (3, 4, 2), (4, 2, 3), (4, 3, 2)]