Kostya
Kostya

Reputation: 1656

Why does this script works?

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 that 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 that this is the wrong way to read the file, but how does the variable line can be used inside the body of the cycle and why list was not constructed first? So it would be really interesting if some one will tell in details how this code work.

Upvotes: 3

Views: 76

Answers (1)

glglgl
glglgl

Reputation: 91017

For each run of the while loop, a temporary and unnamed list is called with the next line as sole content ([f.readline()]). This one is iterated over and line gets assigned the line content.

The outer list comprehension gets [] if not line and [1] if line. This determines if the while loop is continued or not.

Due to the nature of implementing list comprehension in Python 2, line leaks out of the list comprehension into the local name space of the function.

I don't see where a list wasn't created where it should be: there are 2 lists involved which take part either in iteration or in an emptiness check and are discarded after use.

Upvotes: 1

Related Questions