Harsh Trivedi
Harsh Trivedi

Reputation: 1624

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 : )

Upvotes: 1

Views: 160

Answers (1)

karthikr
karthikr

Reputation: 99670

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)]

Upvotes: 5

Related Questions