[Python-Dev] Use for enumerate()

Greg Ball gball@cfa.harvard.edu
Fri, 26 Apr 2002 23:13:41 -0400 (EDT)


On Fri, 26 Apr 2002, Guido van Rossum wrote:


>     def getline(filename, lineno):
> 	if lineno < 1:
> 	    return ''
> 	lineno -= 1
> 	f = open(filename)
> 	for i, line in enumerate(f):
> 	    if i == lineno:
> 		break
> 	else:
> 	    line = ''
> 	f.close()
> 	return line
> 
> 
> Challenge 2: do it with less code.

     def getline(filename, lineno):
 	if lineno < 1:
 	    return ''
 	f = open(filename)
 	for line in f:
 	    lineno -= 1
 	    if not lineno:
 		break
 	else:
 	    line = ''
 	f.close()
 	return line


--
Greg Ball