#### [SOLVED] How can I gradually morph one list into another (cartesian product of 2 lists)?

By Jono

Say I have two lists,

``````one = ['a1', 'b1', 'c1']
two = ['a2', 'b2', 'c2']
``````

I want to generate a collection of all possible combinations of these items, without changing their positions in their respective lists. So for the example above, it'd be:

``````['a1', 'b1', 'c1']
['a1', 'b1', 'c2']
['a1', 'b2', 'c2']
['a2', 'b1', 'c1']
['a2', 'b2', 'c1']
['a2', 'b2', 'c2']
``````

I'm looking through `itertools` hoping to find something that matches this description, but I haven't found one yet.

#### @Rory Daulton 2018-07-12 00:05:47

The function you are looking for is `product` but you need to set it up first. The problem is that you have your values "sideways"--you want to put all possible values for the first position together, then those for the second, etc. You can "transpose" your data with the `*zip()` maneuver.

``````from itertools import product
list(product(*zip(one, two)))
``````

The result from that is

``````[('a1', 'b1', 'c1'),
('a1', 'b1', 'c2'),
('a1', 'b2', 'c1'),
('a1', 'b2', 'c2'),
('a2', 'b1', 'c1'),
('a2', 'b1', 'c2'),
('a2', 'b2', 'c1'),
('a2', 'b2', 'c2')]
``````

If you really want lists rather than tuples, use

``````[list(v) for v in product(*zip(one, two))]
``````

which gives you

``````[['a1', 'b1', 'c1'],
['a1', 'b1', 'c2'],
['a1', 'b2', 'c1'],
['a1', 'b2', 'c2'],
['a2', 'b1', 'c1'],
['a2', 'b1', 'c2'],
['a2', 'b2', 'c1'],
['a2', 'b2', 'c2']]
``````

Note that these are not exactly what you listed as the desired output, since you left out a couple of possibilities.

#### @Prune 2018-07-12 00:06:47

I was going to walk through the logic step by step, but this summary is enough. Deleted my answer draft. :-)

#### @Jono 2018-07-12 00:06:55

This is what I was looking for! Thanks!

### [SOLVED] How do I list all files of a directory?

• 2010-07-08 19:31:22
• duhhunjonn
• 2573992 View
• 2925 Score
• Tags:   python directory

### [SOLVED] How to concatenate two lists in Python?

• 2009-11-12 07:04:09
• y2k
• 1465240 View
• 1699 Score
• Tags:   python list

### [SOLVED] How do I check if a list is empty?

• 2008-09-10 06:20:11
• Ray Vega
• 1816972 View
• 2814 Score
• Tags:   python list is-empty

### [SOLVED] How to get the number of elements in a list in Python?

• 2009-11-11 00:30:54
• y2k
• 2582641 View
• 1587 Score