-2

How do you find all permutations of a list with 3 elements in Python?

For example, input

[1, 2, 3, 4]

would return

[1, 2, 3]
[1, 2, 4]
[1, 3, 4]
[2, 3, 4]

Thanks!

qq121
  • 21
  • 1
  • 4
  • try looking at `itertools.permutations` – sshashank124 Mar 19 '14 at 23:48
  • 4
    Literally the first thing that popped up in a google search. Please do some research before asking a question. http://stackoverflow.com/questions/104420/how-to-generate-all-permutations-of-a-list-in-python – asdf Mar 19 '14 at 23:49
  • OP wanted combinations not permutations like he said, so, he was confused and needed help. I absolutely think this was a question for this site. – CornSmith Jul 18 '14 at 16:20

1 Answers1

6

You want to use itertools.combinations and a list comprehension:

>>> from itertools import combinations
>>> lst = [1, 2, 3, 4]
>>> [list(x) for x in combinations(lst, 3)]
[[1, 2, 3], [1, 2, 4], [1, 3, 4], [2, 3, 4]]
>>>

Regarding your comment, you would make that list of strings by adding in str.join and map*:

>>> from itertools import combinations
>>> lst = [1, 2, 3, 4]
>>> [''.join(map(str, x)) for x in combinations(lst, 3)]
['123', '124', '134', '234']
>>>

*Note: You need to do map(str, x) because str.join requires an iterable of strings.