Python merging two lists with all possible permutations Python merging two lists with all possible permutations python python

Python merging two lists with all possible permutations


repeat the first list, permutate the second and zip it all together

>>> from itertools import permutations, repeat>>> a = [1, 2, 3]>>> b = [4, 5, 6]>>> list(list(zip(r, p)) for (r, p) in zip(repeat(a), permutations(b)))[[(1, 4), (2, 5), (3, 6)], [(1, 4), (2, 6), (3, 5)], [(1, 5), (2, 4), (3, 6)], [(1, 5), (2, 6), (3, 4)], [(1, 6), (2, 4), (3, 5)], [(1, 6), (2, 5), (3, 4)]]

EDIT: As Peter Otten noted, the inner zip and the repeat are superfluous.

[list(zip(a, p)) for p in permutations(b)]


The accepted answer can be simplified to

a = [1, 2, 3]b = [4, 5, 6][list(zip(a, p)) for p in permutations(b)]

(The list() call can be omitted in Python 2)


Try to use list generator to create the nested lists:

>>> [[[x,y] for x in list1] for y in list2][[[1, 3], [2, 3]], [[1, 4], [2, 4]]]>>>

Or, if you want one-line list, just delete brackets:

>>> [[x,y] for x in list1 for y in list2][[1, 3], [1, 4], [2, 3], [2, 4]]