2

Say I have a list that contains n lists. Is there a neat way get all possible combinations of those lists that have length n, each element keeping it's position.

Here's an example:

lists=[[1],[2,3],[4,5]]

output:

[[1,2,4],
 [1,3,4],
 [1,2,5],
 [1,3,5]]
Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
root
  • 76,608
  • 25
  • 108
  • 120

2 Answers2

14

You can use itertools.product for this:

>>> import itertools
>>> lists = [[1], [2, 3], [4, 5]]
>>> list(itertools.product(*lists))
[(1, 2, 4), (1, 2, 5), (1, 3, 4), (1, 3, 5)]
Andrew Clark
  • 202,379
  • 35
  • 273
  • 306
0

Here is the first thing that came to mind:

def find_permutations(lists, context):
    if len(lists) == 1:
        for item in lists[0]:
            yield context + [item]
    else:
        for item in lists[0]:
           for permutation in find_permutations(lists[1:], context + [item]):
               yield permutation
jlund3
  • 648
  • 5
  • 16