1

I want to generate a wordlist by list of list of character, like:

A=[['a','b','c'],['d'],['e','f']]

where a[0] stores all possible character at first place, a[1] stores all possible character at second place and so on. All possible words generated by list 'A' will be:

ade
adf
bde
bdf
cde
cdf

I am generating this list by:

for i in a[0]:
    for j in a[1]:
        for k in a[2]:
            print i+j+k

This code works fine for fixed length of list(i.e. len(A)). I want to write a generalize code which can generate wordlist by list of any size.

admdrew
  • 3,790
  • 4
  • 27
  • 39
  • If question is not clear: I want to pass list of different length like: A=[['w','x','y'],['z']] OR A=[['a','b'],['d','e'],['k'],['l','m']] – Lokesh Pawar Nov 11 '14 at 14:34

1 Answers1

3

You can do this with itertools.product:

>>> from itertools import product
>>> characters = [['a','b','c'],['d'],['e','f']]
>>> [''.join(item) for item in product(*characters)]
['ade', 'adf', 'bde', 'bdf', 'cde', 'cdf']

This will work irrespective of the lengths of the sublists, as the product method computes a Cartesian product of the elements of sublist. Also, since we are passing the sublists with python *characters magic, we can pass any number of sublist.

Anshul Goyal
  • 73,278
  • 37
  • 149
  • 186