Simple looping question...

Remco Gerlich scarblac at pino.selwerd.nl
Tue Apr 3 03:10:20 EDT 2001


David Allen <mda at idatar.com> wrote in comp.lang.python:
> I didn't mean in that case.  It's clear that 
> foo = file.readlines()
> creates an array and puts it in foo.  I was talking
> about in the case of:
> 
> for line in file.readlines():
>   print line
> 
> There, python has two choices.  It could either
> create an entire array holding the entire file, and
> loop through assigning each member of the array to
> line each go through.  Or, it could not allocate
> an array at all, and just treat that statement as
> the equivalent of a long series of file.readline()
> statements.

It has no choice. At it is, Python always does exactly what it looks like it
does. The for loop has no idea what it's looping over, and doesn't need to
know. It first evaluates "file.readlines()" (which results in the list) then
it starts iterating over it. It's not as if "file.readlines()" is part of
the language, it's just a library function.

>From 2.1 onwards, file.xreadlines() is smart by itself, and very fast as well.

-- 
Remco Gerlich



More information about the Python-list mailing list