All possible combinations of the items in n lists

I need to develop a list that contains all possible combinations in order of the elements in n lists. Basically I'm trying to find all the possible paths, which I will need later for another part of my program.

I've already made some simple code for two lists, but the problem is that I don't know how many inputs will the user give, so I have to guess. For the moment I've defined a function that outputs all possible combinations (1 way only, because they're paths). I've been also testing other alternatives like itertools (which I think may hold the answer to my problem), or using numpy arrays (the problem with this is that my array isn't homogeneous).

The input list may look something like this (3 dimensions):

chords = [[[1, 4, 8, 12], [1, 4, 10, 12]], [[4, 7, 13, 19], [4, 9, 13, 21]]]

My function that could generate the permutations between two lists:

def combination(list1, list2):
    list = []
    for x in list1:
        for y in list2:
            list.append([x,y])
    return list

combination(chords[0], chords[1])

This function works as intended, but the problem is for example when I introduce combination(combination(chords[0], chords[1]), chords[3]), which doesn't count separately chords[0] and chords[1] (still, it works as intended).

Edit:

Okay, so like @iBug pointed out, a good way to do it is with itertools.product():

bases_chords = [···] #It's a three dimensional array I've filled out  before
possibilities = [] #The list that will contain all the different combinations

for a in product(*bases_chords): #The asterisk means that I input everything on the list
    possibilities.append(a)

print(possibilities)
print(len(possibilities)) #Just to check if the dimensions are right

Upvotes: 2

Views: 252

Answers (1)

iBug
iBug

Reputation: 37307

itertools.product is what you're looking for. It takes multiple Iterables (lists are iterables) and produces a generator that loops over all combinations for each of them.

See example:

>>> for a, b, c in itertools.product([1, 2, 3], "abc", [True, False]):
...  print(a, b, c)
...
1 a True
1 a False
1 b True
1 b False
1 c True
1 c False
2 a True
2 a False
2 b True
2 b False
2 c True
2 c False
3 a True
3 a False
3 b True
3 b False
3 c True
3 c False
>>>

So your use case would turn into:

itertools.product(*chords)

Upvotes: 2

Related Questions