Search code examples
pythonmathpermutation

All conditional permutations of a nested list in python


I have an array like bellow (A) and I want to convert it to (B).

A:

A = [['a', 'ae', 'oa'], ['a'], ['l'], ['y', 'i']]

B:

B = ['aaly',
'aali',
'aealy',
'aeali',
'oaaly',
'oaali']

Solution

  • Use:

    from itertools import product
    
    A = [['a', 'ae', 'oa'], ['a'], ['l'], ['y', 'i']]
    
    res = ["".join(p) for p in product(*A)]
    print(res)
    

    Output

    ['aaly', 'aali', 'aealy', 'aeali', 'oaaly', 'oaali']
    

    As an alternative use:

    res = list(map("".join, product(*A)))