Loop-and-a-half (Re: Curious assignment behaviour)

Paul Winkler slinkp23 at yahoo.com
Thu Oct 11 21:27:32 CEST 2001


On 11 Oct 2001 16:55:05 GMT, Donn Cave <donn at u.washington.edu> wrote:
>There are plenty of applications for a separate entry, and that's
>where we came in.  The most frequently cited application for an
>assignment expression is
>
>   while line = file.readline():
>      ...

That's not a very compelling example anymore. Presumably you don't
want to do "for line in file.readlines()" because of the memory
implications of slurping the whole file? Well, as of python 2.1 we can
get one line at a time like this:

for line in file.xreadlines():
   ...

And as of Python 2.2, files have an iterator that lets us do it like this:

for line in file:
    ...

Of course, we've already had the xreadlines module for quite a while,
but the new sugary way to do it is easier to remember.


- Paul Winkler









More information about the Python-list mailing list