Michael
Michael

Reputation: 93

Python generate all n-permutations of n lists

I have n lists of different lengths of wich I want to create all possible permutations.

so e.g. if a=[1,2] and b=[3,4,5] then I would love to obtain res=[[1,3],[1,4],[1,5],[2,3],[2,4],[2,5]] I've been trying to achieve this using a recursive function, which turned out to be neither very efficient nor very pythonic. How would an experienced python programmer tackle the problem?

Upvotes: 3

Views: 560

Answers (3)

BWStearns
BWStearns

Reputation: 2706

itertools is definitely the way to go but if you don't want to go the easy route.....

def print_permutations(lists, perms=[]):
    if not lists:
        print perms
    else:
        current_layer = lists[0]
        remaining_layers = lists[1:]
        for word in current_layer:
            print_permutations(remaining_layers, perms + [word])



l = (('quick', 'lazy'), ('brown', 'black', 'grey'), ('fox', 'dog'))
print_permutations(l)

Upvotes: 0

Anupam
Anupam

Reputation: 717

you can do this by product function in itertools,

import itertools
a = [1,2]
b = [3, 4, 5]
out = list(itertools.product(a,b))
print out
[(1, 3), (1, 4), (1, 5), (2, 3), (2, 4), (2, 5)]

Upvotes: 0

orlp
orlp

Reputation: 117641

It's called the Cartesian product of two sequences.

This is already available in Python as a library function: itertools.product.

Example:

>>> import itertools
>>> a = [1, 2]
>>> b = [3, 4, 5]
>>> list(itertools.product(a, b))
[(1, 3), (1, 4), (1, 5), (2, 3), (2, 4), (2, 5)]

Upvotes: 14

Related Questions