[Tutor] listing all combinations of elements of a list

Alan Gauld alan.gauld at freenet.co.uk
Mon Dec 13 15:07:35 CET 2004

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

     for i in items:
         for j in items:

Is both shorter and faster - no len() function calls.

Or if you want to use indices:

size = len(items)  # only calculate once, it won't change!
lst = []                    # don't use builtin function names for
for i in range(0,size)
     for j in range(i+1,size)
return lst

That saves a lot of len() calls and a comparison.
Also it avoids iterating over the whole list each time.

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

I've tidied up a little but I think nested loops are a necessary evil
this case - although somebody is sure to prove me wrong! :-)


Alan G.

More information about the Tutor mailing list