0

I am looking for a way to generate all combinations of items in a given list with an output of a given count. The inputs will be the list and the number of items in each returned combination. For example:

list = [a, b, c, d]
number of items in output: 2

returns:

[(a, b), (a, c), (a, d), (b, c), (b, d), (c, d)]

The same list with number of items in output: 3

returns:

[(a, b, c), (a, b, d), (a, c, d), (b, c, d)]

note that (a, b) == (b, a) etc.

Thanks!

Emil Brundage
  • 213
  • 3
  • 12
  • 2
    You know, I haven't been a daily reader of SO in a long time, but I thought the rule was that to receive assistance, question-askers have to show a little effort. Otherwise, we're building stuff for people instead of sharing knowledge. – erewok Aug 02 '14 at 19:08

2 Answers2

1

You want itertools.combinations:

>>> list(itertools.combinations(['a', 'b', 'c', 'd'], 2))
[('a', 'b'), ('a', 'c'), ('a', 'd'), ('b', 'c'), ('b', 'd'), ('c', 'd')]
>>> list(itertools.combinations(['a', 'b', 'c', 'd'], 3))
[('a', 'b', 'c'), ('a', 'b', 'd'), ('a', 'c', 'd'), ('b', 'c', 'd')]
dano
  • 91,354
  • 19
  • 222
  • 219
0

itertools has a permutations function as well as combinations.

kylieCatt
  • 10,672
  • 5
  • 43
  • 51