Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - get all combinations of a list

I know that I can use itertools.permutation to get all permutations of size r.

But, for itertools.permutation([1,2,3,4],3) it will return (1,2,3) as well as (1,3,2).

  1. I want to filter those repetitions (i.e obtain combinations)

  2. Is there a simple way to get all permutations (of all lengths)?

  3. How can I convert itertools.permutation() result to a regular list?

like image 509
Bush Avatar asked Jun 18 '13 19:06

Bush


People also ask

How do you find all combinations of a list in Python without Itertools?

To create combinations without using itertools, iterate the list one by one and fix the first element of the list and make combinations with the remaining list. Similarly, iterate with all the list elements one by one by recursion of the remaining list.


1 Answers

Use itertools.combinations and a simple loop to get combinations of all size.

combinations return an iterator so you've to pass it to list() to see it's content(or consume it).

>>> from itertools import combinations
>>> lis = [1, 2, 3, 4]
for i in xrange(1, len(lis) + 1):  #  xrange will return the values 1,2,3,4 in this loop
    print list(combinations(lis, i))
...     
[(1,), (2,), (3,), (4,)]
[(1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4)]
[(1, 2, 3), (1, 2, 4), (1, 3, 4), (2, 3, 4)]
[(1,2,3,4)]
like image 51
Ashwini Chaudhary Avatar answered Sep 24 '22 13:09

Ashwini Chaudhary