Getting all possible combinations of list items

Quinn Dunkan quinn at hork.ugcs.caltech.edu
Mon Sep 24 00:48:27 EDT 2001


On Mon, 17 Sep 2001 00:26:40 -0500, Greg Krohn <volucris at hotmail.com> wrote:
>Does anyone know of how I should go about generating a list whose keys are
>all the possible combinations of the items in another list?
...
>I know I could do this easily with nested 'fors', but that requires me to
>know the length of the set. Is this a case for recursive functions? I hope
>not, those things scare me. BTW, each item in another_list will be unique,
>if that matters.

You've already gotten a lot of non-recursive solutions, which is good since
this is python, not scheme.  But if you can get over your fear of recursion,
you may find it a very congenial way to think of such problems.  A recursive
solution would begin with the observation that the permutations of a list
consist of each of the elements of the list followed by all the permutations
of the rest of the elements.

Translating that into python will not be idiomatic or pretty or efficient, but
it will be simple and thus more likely correct, and may help you think of an
iterative solution.



More information about the Python-list mailing list