Python - List Comprehension Syntax


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:


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


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


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 )


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


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


Related Topic