[Python-Dev] Use for enumerate()

Tim Peters tim.one@comcast.net
Sat, 27 Apr 2002 00:24:46 -0400

[holger krekel]
> measured with your driver script the following code
> is about 10-20% faster than 'g2' and it gets close to
> > > Challenge 3: do it faster and with less code.
> def g3(filename, lineno):
>     if lineno>0:
>         f = file(filename)
>         while lineno>0:
>             read = f.read(1024)
>             count = read.count('\n')
>             lineno-=count or lineno
>         f.close()
>         if lineno<count:
>             return read.split('\n')[lineno+count-1]
>     return ''
> vertically it's one line less but it stretches
> a bit horizontally. But it is more portable :-)

What if (the simplest example of what can go wrong) the first line is more
than 1024 characters long, and the caller asks for lineno 1?   The argument
to f.readlines(5000) is just a hint, and Python does whatever is necessary
under the covers to ensure only complete lines are returned (even if it has
to read millions of bytes to get a full line).  The argument to f.read(1024)
is a maximum, whether or not it finds a newline.

Of course Guido never explicitly said it had to return a correct answer, in
which case I vote for


as both shortest and fastest by any measures <wink>.