[Python-Dev] Use for enumerate() (original) (raw)

Guido van Rossum guido@python.org
Sat, 27 Apr 2002 09:26:17 -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 ''

Cute, but it builds up a list containing all the lines up to lineno. An implicit part of the exercise (sorry for not making this explicit) was to avoid this -- IOW it should work even if the file is too large to fit in memory (as long as each individual line fits in memory).

--Guido van Rossum (home page: http://www.python.org/~guido/)