Nested For Loops Using List Comprehension

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.

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

Essentially, you can have as many independent ‘for x in y’ clauses as you want in a list comprehension just by sticking one after the other.

To make it more readable, use multiple lines:

lst = [
       j + k         # result
       for j in s1   # for loop 
         for k in s2 # for loop
                     # condition   
       ]

Leave a Comment