Iterating over readlines() and map()

alex23 wuwei23 at gmail.com
Thu Mar 26 05:03:43 CET 2009


On Mar 26, 10:27 am, "W. Martin Borgert" <deba... at debian.org> wrote:
> Is this also true for this code?
>
> for line in map(myfunction, myfile.readlines()):
>     dosomethingwith(line)
>
> Or would use of map() mean, that the complete "myfile" is read into
> the RAM?

As Christian explained, you're really after just 'myfile' rather than
'myfile.readlines()' here.

The map() built-in, at least for 2.x, produces a list. I think you'll
get the result you're after if you use itertools.imap, which returns
an iterator instead. Or if you don't want to import another function,
you can just use a generator expression:

  for line in (myfunction(l) for l in myfile):
     ...




More information about the Python-list mailing list