[Tutor] listing all combinations of elements of a list

Bill Kranec billk at fastmail.fm
Sun Dec 12 21:51:56 CET 2004

Is there a module containing a function for listing the unique k-element 
subsets of an n-item list?  I have written some code (right now I only 
need it for 2 element subsets):

def combination(items)
    list = []
    for i in range(0,len(items)):
       for j in range(0,len(items)):
          if j > i:
    return list

My problems with this code being that a) code I write is usually pretty 
inefficient, b) it doesn't extend to subsets of size > 2, and c) it uses 
nested loops, which I have gathered from some previous discussions on 
this list to be less than ideal.

Any thoughts on how to improve / replace this code would be appreciated.



More information about the Tutor mailing list