Harsh Trivedi Harsh Trivedi - 4 months ago 19
Ruby Question

Python equivalent for Ruby combination method

Is there idiomatic python way to list all combinations of specific size from a list?

The following code works in ruby (here), I wonder if there is python equivalent for this:

a = [1, 2, 3, 4]
a.combination(1).to_a #=> [[1],[2],[3],[4]]
a.combination(2).to_a #=> [[1,2],[1,3],[1,4],[2,3],[2,4],[3,4]]
a.combination(3).to_a #=> [[1,2,3],[1,2,4],[1,3,4],[2,3,4]]


PS: I am not looking for permutations, but combinations of specific size.

Thanks a lot : )

Answer

The itertools module has a combinations method which does this for you.

itertools.combinations(a, len)

Demo:

>>> a = [1, 2, 3, 4]
>>> import itertools
>>> itertools.combinations(a, 2)
<itertools.combinations object at 0x109c276d8>
>>> list(itertools.combinations(a, 2))
[(1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4)]
>>> list(itertools.combinations(a, 3))
[(1, 2, 3), (1, 2, 4), (1, 3, 4), (2, 3, 4)]
>>> list(itertools.combinations(a, 4))
[(1, 2, 3, 4)]