Python - List Comprehension with if filter

Introduction

Each for clause can have an associated if filter:

Demo

d = [x + y for x in 'test' if x in 'sm' for y in 'TEST' if y in ('P', 'A')] 
print( d )# from   www  .j  a v a 2s . co m

d=[x + y + z for x in 'test' if x in 'sm' 
           for y in 'TEST' if y in ('P', 'A') 
           for z in '123'  if z > '1'] 

print( d )

Result

Use attached if selections on nested for clauses:

Demo

d = [(x, y) for x in range(5) if x % 2 == 0 for y in range(5) if y % 2 == 1] 
print( d )

Result

Here, the code combines even numbers from 0 through 4 with odd numbers from 0 through 4.

The if clauses filter out items in each iteration. Here is the equivalent statement-based code:

Demo

res = [] 
for x in range(5): 
    if x % 2 == 0: 
        for y in range(5): 
            if y % 2 == 1: 
                res.append((x, y)) #  w w w.ja va 2  s. co  m

print( res )

Result

Related Topic