Whiskey Tango Foxtrot - 11 months ago 40

Python Question

I have few lists:

`a = [1,2,3]`

b = [4,5,6]

c = [7,8,9,10]

How do I generate all combinations like:

`a[0], b[0]`

a[1], b[1]

a[2], b[2]

a[0], b[0], c[0]

a[1], b[1], c[0]

a[2], b[2], c[0]

a[1], b[1], c[1]

a[2], b[2], c[2]

a[0], b[0], c[3]

a[1], b[1], c[3]

a[2], b[2], c[3]

.....

There can be only one value at a time from each list.

Imagine two or more lists Like a=[1,2,3] and b=[4,5,6] and c=[7,8,9] and I would like all possible pairs like (a[0], b[0]),(a[1], b[1]), (a[0], b[0], c[0])...

Answer Source

As per your example, you seem to want only `abc`

-type permutations. So you either: 1) build your "permutations" explicitly, or 2) build all permutations and filter out those you do not want.

**Explicit construction**

- Build your
`list_of_lists`

, i.e.`[['a1', 'a2', 'a3'], ['b1', 'b2'], ['c1']]`

- Build your permutations. Use
`itertools.product`

, see All combinations of a list of lists - From each of your permutations, you might want to create several, within a loop. E.g., from
`('a1','b1','c1')`

get`('a1','b1','c1')`

and`('a1','b1')`

. That is easy.

You can fill in the gaps.

**Build all and filter out**

... Probably only useful if you need something (slightly) different from what I understood.