[Tutor] question about strip() and list comprehension

Danny Yoo dyoo at hashcollision.org
Tue Apr 8 23:44:26 CEST 2014


> Could someone explain why and how this list comprehension with strip()
> works?
>
> f = open('file.txt')
> t = [t for t in f.readlines() if t.strip()]
> f.close()
> print "".join(t)


Hi Jared,


Let me rewrite this without the list comprehension, while preserving behavior.

######################
inputFile = open('file.txt')
lines = []
for line in inputFile.readlines():
    if line.strip():
        lines.append(line)
inputFile.close()
print "".join(lines)
######################

I am changing the names of the variables from the original code
because I find it very difficult to distinguish 't' from 'f'
sometimes, and because those names are very tied in my mind to
something else entirely ("true" and "false").


Does the above code make more sense to you than the version using the
list comprehension syntax, or is there something there that is still
confusing?


Good luck to you.


More information about the Tutor mailing list