combinations of variable length nested lists

Just van Rossum just at letterror.com
Tue Aug 7 13:53:24 EDT 2001


Mark Robinson wrote:
> 
> ok, thats a bit more eligant (and efficient) than my attempt in my reply
> to Hans :). You really think that can be written in "far fewer lines"?
> 
> thanks alot
> 
> blobby
> 
> I have no idea whether a list
>  > comprehension in place of the second (double)
>  > loop would be faster, because they have sometimes
>  > turned out to be slower in places where you'd
>  > think they'd be faster.)
> 
> What is a list comprehension, just out of interest :), I am always
> looking to reduce my ignorance.

This one uses list comprehensions (it's based on David Ullrich's version):


input = [[1, 2], [4, 5, 6], [8, 9]]

def perm(alist):
    if len(alist) < 2:
        return [[item] for item in alist[0]]
    tails = perm(alist[1:])
    return [[item] + p for item in alist[0] for p in tails]

for x in perm(input):
    print x
print


Just



More information about the Python-list mailing list