Python - List Comprehension Syntax

Introduction

List comprehensions in their simplest form:

[ expression for target in iterable ] 

All other parts are optional.

The general structure of list comprehensions looks like this:

[ expression for target1 in iterable1 if condition1 
            for target2 in iterable2 if condition2 ... 
            for targetN in iterableN if conditionN ] 

This same syntax is used by set and dictionary comprehensions.

The following code uses nested for clauses:

Demo

res = [x + y for x in [0, 1, 2] for y in [100, 200, 300]] 
print( res )

Result

The code above has the same effect as the following nested for loop:

Demo

res = [] 
for x in [0, 1, 2]: 
    for y in [100, 200, 300]: 
        res.append(x + y) # from w  w w.  ja  va 2 s.  com
print( res )

Result

List comprehensions can iterate over any sequence or other iterable type.

Demo

d=[x + y for x in 'test' for y in 'TEST'] 
print( d )

Result

Related Topic