2

I have a python list:

mylist = [1,2,3,4]

and I want to iterate through all possible combinations of these values without beeing dependant on the position, with a size of three, means I want these as iterations:

iteration: 111
iteration: 112
iteration: 113
iteration: 114
iteration: 221 # note, no 211, since the combination of these values already occured as 112
iteration: 222
iteration: 223
iteration: 224
.
.
.

I thought about iterating through the unique values of the list, but still I have not found a simple solution for this issue which, I atleast think, happens often. Maybe there is a nice numpy method for this. How can I achieve this?

Thanks!

MichaelJanz
  • 1,775
  • 2
  • 8
  • 23

1 Answers1

5

Maybe itertools.combinations_with_replacement is what you're looking for:

from itertools import combinations_with_replacement

l = [1, 2, 3, 4]

for c in combinations_with_replacement(l, 3):
    print(c)

Prints:

(1, 1, 1)
(1, 1, 2)
(1, 1, 3)
(1, 1, 4)
(1, 2, 2)
(1, 2, 3)
(1, 2, 4)
(1, 3, 3)
(1, 3, 4)
(1, 4, 4)
(2, 2, 2)
(2, 2, 3)
(2, 2, 4)
(2, 3, 3)
(2, 3, 4)
(2, 4, 4)
(3, 3, 3)
(3, 3, 4)
(3, 4, 4)
(4, 4, 4)
Andrej Kesely
  • 168,389
  • 15
  • 48
  • 91