The pythonic path of a single list with all variations of the sublist

I am sure that there are answers to this simple question, but I really do not know how to formulate it in English (ashamed), so I decided to ask people.

Suppose I have a list of lists:

[['Sometimes'], [' '], ['I'], [' '], ['love', 'hate'], [' '], ['pizza', 'coke']] 

What would be the most pythonic way to get the following conclusion?

 ['Sometimes I love pizza', 'Sometimes I love coke', 'Sometimes I hate pizza', 'Sometimes I hate coke'] 
+7
python combinatorics
source share
2 answers
 from itertools import product options = [['Sometimes'],[' '],['I'],[' '],['love','hate'],[' '],['pizza','coke']] for combo in product(*options): print("".join(combo)) 

gives

 Sometimes I love pizza Sometimes I love coke Sometimes I hate pizza Sometimes I hate coke 
+10
source share

This can be well written using a recursive generator:

 def sentences(lists, i=0, sentence=''): if i == len(lists): yield sentence else: for word in lists[i]: yield from sentences(lists, i + 1, sentence + word) 

And then

 lists = [['Sometimes'],[' '],['I'],[' '],['love','hate'],[' '],['pizza','coke']] for s in sentences(lists): print s 

which prints

 Sometimes I love pizza Sometimes I love coke Sometimes I hate pizza Sometimes I hate coke 

(To get the actual list, list(sentences(lists)) .)

+1
source share

All Articles