Why does this script work?

tmp.txt

line number one
line number two
line number three

      

tmp.py

#!/usr/bin/env python
# coding=utf-8


def _main():
    f = open('tmp.txt')
    while [1 for line in [f.readline()] if line]:
        print line[:-1]


if '__main__' == __name__:
    _main()

      

And this is what happens when I call the script:

me@yazevnul-mac:tmp$ python tmp.py 
line number one
line number two
line number three

      

Yes, I know this is the wrong way to read the file, but how line

can a variable be used inside the body of the loop, and why was the list not created first? So it would be really interesting if someone goes into detail on how this code works.

+3


source to share


1 answer


For each run of the loop while

, a temporary and unnamed list is called with the next line as the only content ( [f.readline()]

). This number is repeated and line

gets the contents of the string.

The notion of an outer list gets []

if not line

and [1]

if line

. This determines whether the while loop continues or not.



Due to the nature of Python 2's implementation of list line

comprehension , it seeps out of list comprehension into the local namespace of the function.

I don't see where the list was not created where it should be: there are two lists that participate either in the iteration or the empty check and are discarded after use.

+1


source







All Articles