0

If I have a list like:

a = ['AB', ['CD', 'DE'], 'FG']

How do I transform it to a 2D list as shown:

[['AB', 'CD', 'FG'], ['AB', 'DE', 'FG']]

Using itertools.product also expands 'AB' to 'A', 'B'.

2 Answers2

1

You can use itertools.product as follows:

>>> list(itertools.product(*(x if isinstance(x, list) else [x] for x in a)))
[('AB', 'CD', 'FG'), ('AB', 'DE', 'FG')]

Here we simply take the product, where we first transform singletons such as 'AB' into a list ['AB'].

If you require a list of lists for your output, simply transform them:

>>> [list(x) for x in itertools.product(
...      *(x if isinstance(x, list) else [x] for x in a))]
[['AB', 'CD', 'FG'], ['AB', 'DE', 'FG']]
donkopotamus
  • 22,114
  • 2
  • 48
  • 60
0

Here's what I came up with:

b = []
for i in range(len(a)):
  if type(a[i]) is list:
    for j in range(len(a[i])):
      b.append(a[:i] + [a[i][j]] + a[i+1:])