permutations of two lists in python

You want the itertools.product method, which will give you the Cartesian product of both lists.

>>> import itertools
>>> a = ['foo', 'bar', 'baz']
>>> b = ['x', 'y', 'z', 'w']

>>> for r in itertools.product(a, b): print r[0] + r[1]
foox
fooy
fooz
foow
barx
bary
barz
barw
bazx
bazy
bazz
bazw

Your example asks for the bidirectional product (that is, you want ‘xfoo’ as well as ‘foox’). To get that, just do another product and chain the results:

>>> for r in itertools.chain(itertools.product(a, b), itertools.product(b, a)):
...   print r[0] + r[1]

Leave a Comment