Creating unique combinations from lists

Matimus mccredie at gmail.com
Wed Jan 16 16:25:12 EST 2008


On Jan 16, 11:15 am, breal <hacker.steven... at gmail.com> wrote:
> I have three lists... for instance
>
> a = ['big', 'small', 'medium'];
> b = ['old', 'new'];
> c = ['blue', 'green'];
>
> I want to take those and end up with all of the combinations they
> create like the following lists
> ['big', 'old', 'blue']
> ['small', 'old', 'blue']
> ['medium', 'old', 'blue']
> ['big', 'old', 'green']
> ['small', 'old', 'green']
> ['medium', 'small', 'green']
> ['big', 'new', 'blue']
> ['small', 'new', 'blue']
> ['medium', 'new', 'blue']
> ['big', 'new', 'green']
> ['small', 'new', 'green']
> ['medium', 'new', 'green' ]
>
> I could do nested for ... in loops, but was looking for a Pythonic way
> to do this.  Ideas?

I would probably just create a generator:

def permute(a,b,c):
    for x in a:
        for y in b:
            for z in c:
                yield [x,y,z]

all_combos = list(permute(
    ['big', 'small', 'medium'],
    ['old', 'new'],
    ['blue', 'green']))

print all_combos


I'm using nested for loops, but I sure find it easy to read that way.
Though, using list comprehension does pretty much the same thing. It
appears that Tim Chase has posted a more generic version of the above.

Matt



More information about the Python-list mailing list