-2

If I have 3 list [0, 1, 2], [3, 4, 5], [6, 7, 8], how would I obtain an output of a list of lists that are of length three and contain one element from each list and has all possible combinations?

For example, one of the possible combinations of the above is [1, 5, 6].

I tried using numpy.meshgrid, but that only gave me some possible combinations and not all.

eyllanesc
  • 235,170
  • 19
  • 170
  • 241
  • 2
    Possible duplicate: [Get the cartesian product of a series of lists?](https://stackoverflow.com/questions/533905/get-the-cartesian-product-of-a-series-of-lists) – manveti Nov 22 '19 at 23:44

1 Answers1

4
import itertools
x = [[0, 1, 2], [3, 4, 5], [6, 7, 8]]
all_combinations = list(itertools.product(*x))
[(0, 3, 6),
 (0, 3, 7),
 (0, 3, 8),
 (0, 4, 6),
 (0, 4, 7),
 (0, 4, 8),
 (0, 5, 6),
 (0, 5, 7),
 (0, 5, 8),
 (1, 3, 6),
 (1, 3, 7),
 (1, 3, 8),
 (1, 4, 6),
 (1, 4, 7),
 (1, 4, 8),
 (1, 5, 6),
 (1, 5, 7),
 (1, 5, 8),
 (2, 3, 6),
 (2, 3, 7),
 (2, 3, 8),
 (2, 4, 6),
 (2, 4, 7),
 (2, 4, 8),
 (2, 5, 6),
 (2, 5, 7),
 (2, 5, 8)]
CHINTAN VADGAMA
  • 634
  • 7
  • 13
  • 1
    Thanks so much for your response! I didn't realize this was a duplicate because I didn't know what a cartesian product is. Thanks again! – sexytoasteroven Nov 22 '19 at 23:54