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.

1 comments

@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

10 Answered Questions

11 Answered Questions

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

25 Answered Questions

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

32 Answered Questions

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

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

28 Answered Questions

[SOLVED] How to concatenate two lists in Python?

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

58 Answered Questions

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

27 Answered Questions

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

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

34 Answered Questions

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

6 Answered Questions

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

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

18 Answered Questions

[SOLVED] How to clone or copy a list?

Sponsored Content