0

I was wondering how to get all the possible combinations from a list with n-length from python. But there is one catch. It's hard for me to explain as English is not my native language. So I give an example:

If I have a list:

my_List = [1, 2, 3, 4]

I want it to get an output of with length 3 to be

(1, 1, 1)
(1, 1, 2)
(1, 1, 3)
(1, 1, 4)
etc etc

But I do NOT want to have repeated lists. By that I mean, if I already have

(1, 1, 2)

I do not have any need for

(1, 2, 1) and
(2, 1, 1)

Does that make any sence? Any help woudl be much apreciated

user3685412
  • 4,057
  • 3
  • 16
  • 16
  • [`itertools.combinations()`](https://docs.python.org/2/library/itertools.html#itertools.combinations) – Sven Marnach Jul 02 '14 at 16:50
  • http://stackoverflow.com/questions/464864/python-code-to-pick-out-all-possible-combinations-from-a-list – kasparg Jul 02 '14 at 16:51
  • I deleted my answer. falsetru is correct, you want `combinations_with_replacement`, not `combinations`. – Weeble Jul 03 '14 at 09:47

1 Answers1

1

Use itertools.combinations_with_replacement:

>>> import itertools
>>> my_List = [1, 2, 3, 4]
>>> for xs in itertools.combinations_with_replacement(my_List, 3):
...     print(xs)
...
(1, 1, 1)
(1, 1, 2)
(1, 1, 3)
(1, 1, 4)
(1, 2, 2)
(1, 2, 3)
...
falsetru
  • 357,413
  • 63
  • 732
  • 636