Creating a list of lists where each sublist contains one element from an input sequence of lists

Viewed 233

Given an arbitrary set of lists, I need to create a nested lists containing unique elements from each input list.

For example, given [1,2], [3,4], [5,6,8], I want the output to be [ [1,3,5], [1,3,6], [1,3,8], [1,4,5], [1,4,6], [1,4,8], [2,3,5], [2,3,6], [2,3,8], [2,4,5], [2,4,6], [2,4,8] ] - 12 lists in the list of lists.

The input can be any number of lists with any number of elements within each list (in the given example, we have 3 lists with a maximum of 3 elements in a single list => 2*2*3 = 12)

I need to write a program with the best possible time complexity.

1 Answers

You can use itertools.product() with list unpacking:

from itertools import product
data = [[1,2], [3,4], [5,6,8]]

for item in product(*data):
    print(list(item))

This outputs:

[1, 3, 5]
[1, 3, 6]
[1, 3, 8]
[1, 4, 5]
[1, 4, 6]
[1, 4, 8]
[2, 3, 5]
[2, 3, 6]
[2, 3, 8]
[2, 4, 5]
[2, 4, 6]
[2, 4, 8]
Related