Pulling all n-sized combinations from a list

Swroteb swrittenb at gmail.com
Wed Feb 8 15:50:19 EST 2006


Hi there,

I've got a reasonably sized list of objects that I'd like to pull out
all combinations of five elements from.  Right now I have a way to do
this that's quite slow, but manageable.  I know there must be a better
way to do this, but I'm not sure what it is.  Here's what I've got so
far:

        for a in myList:
            for b in myList:
                if a == b:
                    break
                for c in myList:
                    if b == c:
                        break
                    for d in myList:
                        if c == d:
                            break
                        for e in myList:
                            if d == e:
                                break
                            # my code here.

Atrocious and slow, I'm sure, but is there a better way?  I can't
simply create a list with the combinations I want, since it won't fit
into memory.  And I'm sure I can do it using a standard paradigm using
five indexed for loops (ie, for i = 1, for j = i+1, for k = j+1, etc.).
 But is there a really nice way to handle this in Python?

Thanks for your time!
Scott




More information about the Python-list mailing list