-1

I have N number of lists (or sets), the number N which I do not know. I have to access one element from each list to check for a condition.

For eg, if

A = [1, 2, 3] 
B = [5, 6]  
c = [6, 7] 

my combinations would be [(1,5,6), (1,5,7), (1,6,6), (1,6, 7), (2, 5, 6) and so on...]

How to do this efficiently?

list1 = [(i, j, k) for i in listx for j in listy for k in listz]

works for known N (here 3); How to do this for unknown N?

Rahul charan
  • 765
  • 7
  • 15
  • 2
    Possible duplicate of [Cartesian product of two lists in python](https://stackoverflow.com/questions/52192855/cartesian-product-of-two-lists-in-python) and [Get the cartesian product of a series of lists?](https://stackoverflow.com/questions/533905/get-the-cartesian-product-of-a-series-of-lists) – Devesh Kumar Singh Jun 23 '19 at 08:39

2 Answers2

0

you are exactly describing a Cartesian Product try itertools.product:

from itertools import product

A = [1, 2, 3]
B = [5, 6]
C = [6, 7]

print(list(product(A,B,C)))


Adam.Er8
  • 12,675
  • 3
  • 26
  • 38
0

you can use product from itertools for an arbitary number of lists :

from itertools import product
lists = [[1, 2, 3], [3,2,1],[2,3],[1,5,4]]
print([*product(*lists)])
# [(1, 3, 2, 1), (1, 3, 2, 5), (1, 3, 2, 4) ...
Ayoub ZAROU
  • 2,387
  • 6
  • 20