Python - List Comprehension Filter clauses: if


The for loop nested in a comprehension expression can have an associated if clause to filter out of the result items.

For example, to filter a file and collect only lines that begin with the letter p.

Adding an if filter clause to our expression does the trick:


lines = [line.rstrip() for line in open('') if line[0] == 'p'] 
print( lines )


Here, the if clause checks each line read from the file to see whether its first character is p.

If not, the line is omitted from the result list.

for loop statement equivalent is listed as follows.

res = [] 
for line in open(''): 
    if line[0] == 'p': 
print( res )

The following code selects only lines that end in a digit.

It uses a more sophisticated expression on the right side:


print( [line.rstrip() for line in open('') if line.rstrip()[-1].isdigit()] )


Related Example