Crate a List of elements from different combination of list iltems

Viewed 41

I have N number of List. Here, I am giving two examples.

List_1 = [5,6,7,8,9,10]
List_2 = [5,6,7,8,9,10]

I want to create a List of tuple from this N number of list. For two elements of list output should be,

 [(5,),(6,),(7,),(8,),(9,),(10,),(5,5,),(5,6)....(5,10),(6,5,),(6,6)....(6,10),(7,5,),(7,6)....(7,10)
.............(10,10)]

The output element is 1 to N number of elements pair using all combinations of list elements.

List_1 = [5,6,7,8,9,10]
List_2 = [5,6,7,8,9,10]
List_3 = [5,6,7,8,9,10]

For 3 list element output is,

 [(5,),(6,),(7,),(8,),(9,),(10,),(5,5,),(5,6)....(5,10),(6,5,),(6,6)....(6,10),(7,5,),(7,6)....(7,10)
.............(10,10),(5,5,5)..(all combination of 1 ,2 & 3 elements items of three list)...(10,10,10)] 

Note: All list have the same value

1 Answers

This could be a possible solution:

from itertools import product

#since the lists have the same value, we need to save it once and decide how many times repeat the product
List_1 = [5,6,7,8,9,10]
list_repetition = 2

result = []
for i in range(list_repetition):
    result.extend(tuple(product(List_1, repeat=i+1)))
    
print(result)

And the output will be:

[(5,), (6,), (7,), (8,), (9,), (10,), (5, 5), (5, 6), (5, 7), (5, 8), (5, 9), (5, 10), (6, 5), (6, 6), (6, 7), (6, 8), (6, 9), (6, 10), (7, 5), (7, 6), (7, 7), (7, 8), (7, 9), (7, 10), (8, 5), (8, 6), (8, 7), (8, 8), (8, 9), (8, 10), (9, 5), (9, 6), (9, 7), (9, 8), (9, 9), (9, 10), (10, 5), (10, 6), (10, 7), (10, 8), (10, 9), (10, 10)]
Related