# [Tutor] listing all combinations of elements of a list

Jacob S. keridee at jayco.net
Sun Dec 19 04:16:21 CET 2004

```Am I wrong, or is that what the module sets is for? I don't remember if
python 2.3 has it, but python2.4 has it available.

>>> import sets
>>> s = sets.Set
>>> a = s([1,2,3])
>>> a
Set([1, 2, 3])
>>> a.update([1,1,2,2,3,3,4,4,5,5])
>>> a
Set([1, 2, 3, 4, 5])
>>>

HTH,
Jacob Schmidt

> > 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
> variables
> for i in range(0,size)
>      for j in range(i+1,size)
>            lst.append(....)
> 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
> 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.
>
> I've tidied up a little but I think nested loops are a necessary evil
> in
> this case - although somebody is sure to prove me wrong! :-)
>
> HTH,
>
> Alan G.
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>

```