Looking under Python's hood: Will we find a high performance or clunky engine?
Robert Kern
robert.kern at gmail.com
Sun Jan 22 13:01:11 EST 2012
On 1/22/12 3:50 PM, Rick Johnson wrote:
>
> What does Python do when presented with this code?
>
> py> [line.strip('\n') for line in f.readlines()]
>
> If Python reads all the file lines first and THEN iterates AGAIN to do
> the strip; we are driving a Fred flintstone mobile. If however Python
> strips each line of the lines passed into readlines in one fell swoop,
> we made the correct choice.
>
> Which is it Pythonistas? Which is it?
The .readlines() method is an old API that predates the introduction of
iterators to Python. The modern way to do this in one iteration is to use the
file object as an iterator:
[line.strip('\n') for line in f]
--
Robert Kern
"I have come to believe that the whole world is an enigma, a harmless enigma
that is made terrible by our own mad attempt to interpret it as though it had
an underlying truth."
-- Umberto Eco
More information about the Python-list
mailing list