How to get all possible combinations with python

Python is rich with wonderful standard library so you do not have to write everything from the very beginning. With permutations from iterators we can get wonderful and useful result with less code

>In this example code we get the user input as string

> Get the user input length

> Then run a for loop based on the user input str length

> get the combinations with permutation with store the combination in a list

Like this

Enter your word or sentence or number: 123
['1', '2', '3', '12', '13', '21', '23', '31', '32', '123', '132', '213', '231', '312', '321']



from itertools import permutations
user_input=str(input("Enter your word or sentence or number: "))
l=len(user_input)+1
combinations=[]
for i in range(1,l):
	a=list(permutations(user_input,i))
	for element in a:
		x=(''.join(element))
		combinations.append(x)
print(combinations)


We can make this more wonderful to print out with pprint. Also print out all combinations from a list.


from itertools import permutations
from pprint import pprint
# flower names
flower_names = ["rose","orchid", "sunflower"]

l=len(flower_names)+1
combinations=[]
for i in range(1,l):
	a=list(permutations(flower_names,i))
	combinations.append(a)
pprint(combinations)


You will get this result on running this code

[[('rose',), ('orchid',), ('sunflower',)],
 [('rose', 'orchid'),
  ('rose', 'sunflower'),
  ('orchid', 'rose'),
  ('orchid', 'sunflower'),
  ('sunflower', 'rose'),
  ('sunflower', 'orchid')],
 [('rose', 'orchid', 'sunflower'),
  ('rose', 'sunflower', 'orchid'),
  ('orchid', 'rose', 'sunflower'),
  ('orchid', 'sunflower', 'rose'),
  ('sunflower', 'rose', 'orchid'),
  ('sunflower', 'orchid', 'rose')]]