Python - List Comprehension Nested loops: for

Introduction

List comprehensions may contain nested loops, coded as a series of for clauses.

It allows for any number of for clauses, each of which can have an optional associated if clause.

For example, the following builds a list of the concatenation of x + y for every x in one string and every y in another.

It effectively collects all the ordered combinations of the characters in two strings:

Demo

l = [x + y for x in 'abc' for y in 'lmn'] 
print( l )

Result

The above expression can be converted to the following code.

res = [] 
for x in 'abc': 
    for y in 'lmn': 
        res.append(x + y) 

print( res )

Related Example