Nested loops using list comprehension

If I had two lines, 'abc' and 'def' , I could get all of their combinations, using two for loops:

 for j in s1: for k in s2: print(j, k) 

However, I would like to be able to do this using a list comprehension. I tried many ways, but could not. Does anyone know how to do this?

+50
python for-loop list-comprehension
Sep 03 '10 at 4:57
source share
3 answers
 lst = [j + k for j in s1 for k in s2] 

or

 lst = [(j, k) for j in s1 for k in s2] 

if you want tuples.

As in the question, for j... is an outer loop, for k... is an inner loop.

Essentially, you can have as many independent "for x in y" sentences as you want in understanding the list, just sticking one by one.

+81
Sep 03 '10 at 4:58
source share

Since this is essentially a Cartesian product, you can also use itertools.product . I think this is clearer, especially when you have more input iterations.

 itertools.product('abc', 'def', 'ghi') 
+27
Sep 03 '10 at 7:53
source share

Try also recursion:

 s="" s1="abc" s2="def" def combinations(s,l): if l==0: print s else: combinations(s+s1[len(s1)-l],l-1) combinations(s+s2[len(s2)-l],l-1) combinations(s,len(s1)) 

Gives you 8 combinations:

 abc abf aec aef dbc dbf dec def 
0
Mar 24 '14 at 20:53
source share



All Articles