1

I am trying to make possible combinations of 'AB', like:

[('A', 'A'), ('A', 'B'), ('B', 'A'), ('B', 'B')]. 

I'm using itertools.permutations, but its just returning, [('A', 'B'), ('B', 'A')]

What would be the procedure to have both ('A','A') and ('B','B') too.

Also, here I am talking with input 'AB'. What would be the procedure if I had to make combinations of input 'AB', 'BA' such that the output is [('AB','AB'), ('AB, 'BA'), ('BA', 'BA'), ('BA','BA']).

Also, I don't worry about the order.

martineau
  • 119,623
  • 25
  • 170
  • 301
engqureshi
  • 117
  • 1
  • 1
  • 7

2 Answers2

2

The tool from itertools you are looking for is product.

>>> list(itertools.product('AB', repeat=2))
[('A', 'A'), ('A', 'B'), ('B', 'A'), ('B', 'B')]

This will give all possible arrangements of the specified elements that are of length 2 (specified by the repeat keyword). Both permutations and combinations explicitly state that they do not repeat elements. The function itertools.combinations_with_replacement is close to what you want, which allows repeated elements, but only gives distinct combinations, rather than all permutations. The function itertools.permutations_with_replacement doesn't exist, because this is exactly what itertools.product gives you.

K. Nielson
  • 191
  • 9
1

Apart from what Nielson added, you can also obtain the required result without using itertools,

x = 'AB'
l = [(a, b) for a in x for b in x]

This will produce the desired output.