1

I'm trying to get 5 length combinations out of a list of 2 can't find anything that works.

x = [5,7]
abc = list(itertools.combinations((x),5))

All I get is []

Hoping to get every possible combinations of [5,7] but with a length of 5 like [5,7,7,5,7].

Is seems possible, I've tried alot of different things.

once again, thanks for all the help.

Sam c21
  • 253
  • 1
  • 2
  • 9

1 Answers1

3

The reason why you get [] is indeed (as the title suggests) you want a length longer than the number of elements. Whereas, the doc says:

itertools.combinations(iterable, r):

Return r length subsequences of elements from the input iterable.

I guess what you need is another function (next paragraph in the doc):

>>> x = [5, 7]
list(itertools.combinations_with_replacement((x),5))                        
[(5, 5, 5, 5, 5), (5, 5, 5, 5, 7), (5, 5, 5, 7, 7), (5, 5, 7, 7, 7), (5, 7, 7, 7, 7), (7, 7, 7, 7, 7)]
>>> 

Or, as your example suggests, maybe you do not want combinations but permutations? Problem is, it doesn't seem to be possible to do the same as for combinations. But maybe a cartesian product will do the trick?

>>> list(itertools.product(x, repeat=5))
[(5, 5, 5, 5, 5), (5, 5, 5, 5, 7), (5, 5, 5, 7, 5), (5, 5, 5, 7, 7), (5, 5, 7, 5, 5), (5, 5, 7, 5, 7), (5, 5, 7, 7, 5), (5, 5, 7, 7, 7), (5, 7, 5, 5, 5), (5, 7, 5, 5, 7), (5, 7, 5, 7, 5), (5, 7, 5, 7, 7), (5, 7, 7, 5, 5), (5, 7, 7, 5, 7), (5, 7, 7, 7, 5), (5, 7, 7, 7, 7), (7, 5, 5, 5, 5), (7, 5, 5, 5, 7), (7, 5, 5, 7, 5), (7, 5, 5, 7, 7), (7, 5, 7, 5, 5), (7, 5, 7, 5, 7), (7, 5, 7, 7, 5), (7, 5, 7, 7, 7), (7, 7, 5, 5, 5), (7, 7, 5, 5, 7), (7, 7, 5, 7, 5), (7, 7, 5, 7, 7), (7, 7, 7, 5, 5), (7, 7, 7, 5, 7), (7, 7, 7, 7, 5), (7, 7, 7, 7, 7)]

EDIT: isn't your question really really close to this one: python all possible combinations of 0,1 of length k

Community
  • 1
  • 1
zezollo
  • 4,606
  • 5
  • 28
  • 59