Jack Geiger Jack Geiger - 25 days ago 5
Python Question

Avoiding Duplicate Function call in List Comprehension in Python

I would like to iterate through each a file, trim the whitespace for each line, and delete the line if the returned string is empty. Is there a way to avoid duplicating the .strip() call in the list comprehension below? It's not performance-critical but it feels wrong.

sub main():
fname = "foo.txt"
lns = []

with open(fname, 'r') as file:
lns = file.readlines()

newlns = [i.strip() + "\n" for i in lns if i.strip()]
#I want this to look like the following, which doesn't work:
#newlns = [y + "\n" for i in lns if i.strip() as y]

with open("out.txt", 'w') as file:
file.writelines(newlns)

Answer

You can use a nested list comprehension (well, generator expression in this case to avoid actually building a list):

newlns = [i + "\n" for i in (line.strip() for ln in lns) if i]

In fact you really shouldn't even bother to read the file first, just put it in there too: iterating over a file yields its lines.

with open(fname, 'r') as file:
    newlns = [i + "\n" for i in (line.strip() for ln in file) if i]