By Jono

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

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

This is what I was looking for! Thanks!

Related Questions

Sponsored Content

25 Answered Questions

[SOLVED] How to concatenate two lists in Python?

  • 2009-11-12 07:04:09
  • y2k
  • 1372914 View
  • 1620 Score
  • 25 Answer
  • Tags:   python list

27 Answered Questions

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

  • 2008-09-10 06:20:11
  • Ray Vega
  • 1710717 View
  • 2688 Score
  • 27 Answer
  • Tags:   python list is-empty

6 Answered Questions

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

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

13 Answered Questions

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

24 Answered Questions

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

18 Answered Questions

[SOLVED] How to clone or copy a list?

32 Answered Questions

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

  • 2010-07-08 19:31:22
  • duhhunjonn
  • 2409396 View
  • 2773 Score
  • 32 Answer
  • Tags:   python directory

10 Answered Questions

35 Answered Questions

[SOLVED] In Python, how do I read a file line-by-line into a list?

57 Answered Questions

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

Sponsored Content