M.O.
M.O.

Reputation: 496

Generating combinations of a list, all with the same length

Ok so if you use this you get the possible combinations of a list

stuff = [1, 2, 3]
for L in range(0, len(stuff)+1):
    for subset in itertools.combinations(stuff, L):
        print(subset)

And the result is

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

Is there a way to change this so that the result will be

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

or another code that would do this?

Upvotes: 4

Views: 153

Answers (1)

niemmi
niemmi

Reputation: 17273

If the output order doesn't matter you could turn items on stuff to lists of length of 2 where the first number is 0 and use itertools.product:

>>> from itertools import product
>>> stuff = [1, 2, 3]
>>> list(product(*([0, x] for x in stuff)))
[(0, 0, 0), (0, 0, 3), (0, 2, 0), (0, 2, 3), (1, 0, 0), (1, 0, 3), (1, 2, 0), (1, 2, 3)]

Upvotes: 6

Related Questions