combinations of variable length nested lists

Alex Martelli aleax at
Wed Aug 8 14:04:30 CEST 2001

"xauau" <xauau at> wrote in message
news:840bdd8f.0108080216.6dffdbc9 at
> def permute(a):
>     if len(a) == 0: return [[]]
>     return [[x] + y for x in a[0] for y in permute(a[1:])]
> Actually, it needs all of three lines if you count the func def ;-)
> Just for fun, does anyone know how to move the 'if' into the list
> comprehension to make it a one-liner?

It's easy to oneline this function's body _without_ moving
the test inside the list comprehension (it's a long line
so my newsreader might break it, but it's logically one):

return (len(a)==0 and [[]]) or [[x]+y for x in a[0] for y in permute(a[1:])]


More information about the Python-list mailing list