Random Studios
Random Studios

Reputation: 415

How do I get all combinations of a list with repeating values

I have a program that needs to get all possible combinations of items in a list, but what I have found so far doesn't give me what I need. From a list of say [1,2,3] I need the output,

(1)(2)(3)(1,1)(1,2)(1,3)(2,1)(2,2)(2,3)(3,1)(3,2)(3,3)

But all the solutions I've found give me an answer that doesn't repeat values, is there a library that can do this for me, because itertools doesn't give me the right output. Otherwise I'll just right a function myself.

Upvotes: 1

Views: 810

Answers (3)

Ajax1234
Ajax1234

Reputation: 71451

You can use a recursive generator function:

def combos(d, l, c = []):
  yield tuple(c)
  if len(c) < l:
     yield from [i for b in d for i in combos(d, l, c+[b])]

_, *vals = combos([1,2,3], 2)

Output:

[(1,), (1, 1), (1, 2), (1, 3), (2,), (2, 1), (2, 2), (2, 3), (3,), (3, 1), (3, 2), (3, 3)]

Upvotes: 0

Mark Reed
Mark Reed

Reputation: 95267

Your original desired result was just the Cartesian product of the list with itself:

my_list = [1,2,3]
list(itertools.product(my_list, my_list))
#=> [(1, 1), (1, 2), (1, 3), (2, 1), (2, 2), (2, 3), (3, 1), (3, 2), (3, 3)]

But you edited it to include (1,), (2,), and (3,). In that case you may be asking for the power set instead - that's the set of all the subsets of the original. You can use the answers to this question, but be aware that the result will include both the empty list and the original list in its entirety.

Upvotes: 3

Anand Narayanan
Anand Narayanan

Reputation: 83

You can do this with list comprehension:

a = [1,2,3]
[(i,j) for i in a for j in a]

Upvotes: 0

Related Questions