By Jonathan

2018-07-12 00:01:12 8 Comments

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. :-)

@Jonathan 2018-07-12 00:06:55

This is what I was looking for! Thanks!

Related Questions

Sponsored Content

6 Answered Questions

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

  • 2009-11-11 00:30:54
  • y2k
  • 2931732 View
  • 1716 Score
  • 6 Answer
  • Tags:   python list

36 Answered Questions

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

  • 2008-09-10 06:20:11
  • Ray Vega
  • 2047649 View
  • 3074 Score
  • 36 Answer
  • Tags:   python list

25 Answered Questions

[SOLVED] How can I safely create a nested directory in Python?

16 Answered Questions

[SOLVED] How can I make a time delay in Python?

25 Answered Questions

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

  • 2010-07-08 19:31:22
  • duhhunjonn
  • 2940630 View
  • 3235 Score
  • 25 Answer
  • Tags:   python directory

33 Answered Questions

[SOLVED] How to read a file line-by-line into a list?

30 Answered Questions

[SOLVED] How to concatenate two lists in Python?

19 Answered Questions

[SOLVED] How to clone or copy a list?

57 Answered Questions

[SOLVED] How do you split a list into evenly sized chunks?

10 Answered Questions

Sponsored Content