-1

I want to create all possible character combinations from lists. The first char needs to be from the first array, the second char from the second array, etc.

If I have the following lists:

char1 = ['a','b','c']
char2 = ['1','2']

The possible strings, would be: a1, a2, b1, b2, c1 and c2. How do I make the code with makes all the combinations from an unknown amount of lists with an unknown size?

The problem is that I do not know, how many lists there will be. The amount of lists will be decided by the user, while the code is running.

user31751
  • 3
  • 2
  • This one is for an unknown amount of lists, therefore the two list multiplication code isn't useful here. – user31751 Nov 29 '17 at 18:27
  • "The amount of lists will be decided by the user, while the code is running." Then they will certainly not be in separate variables, but in a list of lists instead... **right**? – Karl Knechtel Mar 02 '23 at 03:07

2 Answers2

0

That's a task for itertools.product()! Check out the docs: https://docs.python.org/2/library/itertools.html#itertools.product

>>> ["%s%s" % (c1,c2) for (c1,c2) in itertools.product(char1, char2)]
['a1', 'a2', 'b1', 'b2', 'c1', 'c2']

And yeah, it extends to a variable number of lists of unknown size.

Pavel
  • 7,436
  • 2
  • 29
  • 42
0

As mentioned above, you can use itertools.product()

And since you don't know number of lists you can pass list of lists as an argument:

import itertools

lists = [
    ['a','b','c'],
    ['1','2']
]

["".join(x) for x in itertools.product(*lists)]

Result:

['a1', 'a2', 'b1', 'b2', 'c1', 'c2']
Andrew
  • 36
  • 7