itertools is a powerful modules of python. it has a function named as permutations which prints r length of permutations of a given iterable. Here we will see python itertools permutations example.

#!/usr/bin/python
from itertools import permutations

for string in permutations("abc",2):
	print ' '.join(string)
  • Save the code as perm.py
  • Make it executable by using command ‘chmod +x perm.py’
  • Run using ./perm.py from terminal. its output would be as follows
a b
a c
b a
b c
c a
c b
  • The itertools function permutations do not repeat values if the string (iterable) contains unique characters.
  • The itertools function permutations do repeat values if the string (iterable)  contains duplicate characters. For example if the string is ‘abb’ then it will print ab,ab,ba,bb,ba,bb ( see below example )
#!/usr/bin/python
from itertools import permutations

#create an empty set
s = set()
for string in permutations("abb",2):
	print ''.join(string)

Using python itertools permutations example ( remove duplicates values)

We can use python set for removing duplicate values from the output of itertools permutations function. Below example will print only unique values.

#!/usr/bin/python
from itertools import permutations

#create an empty set
s = set()
for string in permutations("abb",2):
	s.add(''.join(string))

#print items from set s
for item in s:
	print item

Output:
bosch@bosch-Inspiron-N5050:~$ ./perm.py 
ab
ba
bb

 




Related Contents to follow