0

Possible Duplicate:
Python code to pick out all possible combinations from a list?

I have a list say [1, 2, 3]. I want to find the all the combinations

C(3,1)
[1] [2] [3]

C(3,2)
[1,2] [2,3] [1,3]

C(3,3)
[1,2,3]

Is there some module/library for doing this?

Community
  • 1
  • 1
Bruce
  • 33,927
  • 76
  • 174
  • 262

2 Answers2

5

You can use itertools.combinations

>>> import itertools

>>> list(itertools.combinations([1,2,3], 1))
[(1,), (2,), (3,)]

>>> list(itertools.combinations([1,2,3], 2))
[(1, 2), (1, 3), (2, 3)]

>>> list(itertools.combinations([1,2,3], 3))
[(1, 2, 3)]

or generally for your C:

def C(a, b):
    return list(itertools.combinations(range(1,a+1), b))
eumiro
  • 207,213
  • 34
  • 299
  • 261
1

Take a look at the itertools library: http://docs.python.org/library/itertools.html

dj18
  • 384
  • 3
  • 7
  • 19
  • 1
    Even if a link is what is asked for, don't just post a link. Show how to do what he's asking, or at least quote from the source. If all you have to contribute is a link, post it as a comment. – agf Mar 27 '12 at 14:55