Lazy "for line in f" ?

Duncan Booth duncan.booth at invalid.invalid
Mon Jul 23 06:38:29 EDT 2007


Duncan Booth <duncan.booth at invalid.invalid> wrote:

> or even:
> 
>    read = f.readline
>    while read():
>        pass
> 

Oops, I forgot the other obvious variant on this, which has the benefit of 
getting rid of the test I said was 'required' while still leaving the data 
accessible:

    for line in iter(f.readline, ''):
        pass

Takes 8.89 seconds (best of 3 runs) versus 3.56 (best of 3) for the 
similar:

    for line in f:
        pass

So readline is 250% slower at best, and only then if you remember the 
obscure use of iter. :)



More information about the Python-list mailing list