[Python-Dev] Use for enumerate()

Raymond Hettinger python@rcn.com
Sat, 27 Apr 2002 01:08:43 -0400


> Challenge 3: do it faster and with less code.

def getline(filename, lineno):
    if lineno < 1:
        return ''
    f = open(filename)
    i, line = zip(xrange(lineno), f)[-1]
    f.close()
    if i+1 == lineno:
        return line
    return ''

To keep to the spirit of the challenge, I'm ignoring that
the function is i/o bound which would lead to using
an 'rb' read and doing .finds or .counts on '\n'.  

The approach is to vectorize, trading away memory 
allocation time and xrange time to save the overhead 
of the pure Python loop and test cycle.

The test is saved by taking advantage of zip's feature
which stops when the first iterator is exhausted.


Raymond Hettinger