Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 572
Kostya Avatar asked Jul 10 '26 04:07

Kostya


1 Answers

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.

like image 200
glglgl Avatar answered Jul 11 '26 19:07

glglgl



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!