Search code examples
pythonstringalgorithmsubstring

How to return all sub-list from list that contains lists


There is a list in python l1 =['the movie is',['good','bad'],'and it was',['nice','not bad']] So I want The output:

Output:
the movie is good and it was nice
the movie is good and it was not bad
the movie is bad and it was nice
the movie is bad and it was not bad

How Can I do it?


Solution

  • You can do it in one line if you change the single elements to a list as well.

    from itertools import product
    
    l1 = ['the movie is', ['good','bad'], 'and it was', ['nice','not bad']]
    l1 = [item if isinstance(item, list) else [item] for item in l1]
    
    # finding all combinations
    all_combinations = [' '.join(item) for item in product(*l1)]
    
    print(all_combinations)
    
    Output:
    [
        'the movie is good and it was nice',
        'the movie is good and it was not bad',
        'the movie is bad and it was nice',
        'the movie is bad and it was not bad'
    ]
    

    The first line takes care of converting single elements to a list.