an enumerate question

Steven Bethard steven.bethard at
Tue Mar 20 04:00:23 CET 2007

eight02645999 at wrote:
> for n,l in enumerate(open("file")):
>    print n,l # this prints current line
>    print next line in this current iteration of the loop.

Depends what you want to happen when you request "next".  If you want to 
renumber the lines, you can call .next() on the iterator::

     >>> open('temp.txt', 'w').write('1\n2\n3\n4\n5\n6\n7\n')
     >>> lines_iter = open('temp.txt')
     >>> for i, line in enumerate(lines_iter):
     ...     print 'LINE %i, %r %r' % (i, line,
     LINE 0, '1\n' '2\n'
     LINE 1, '3\n' '4\n'
     LINE 2, '5\n' '6\n'
     Traceback (most recent call last):
       File "<interactive input>", line 2, in <module>

If you want to peek ahead without removing the line from the iterator, 
check out this recipe::

Which allows code like::

     >>> lines_iter = peekable(open('temp.txt'))
     >>> for i, line in enumerate(lines_iter):
     ...     print 'LINE %i, %r %r' % (i, line, lines_iter.peek())
     LINE 0, '1\n' '2\n'
     LINE 1, '2\n' '3\n'
     LINE 2, '3\n' '4\n'
     LINE 3, '4\n' '5\n'
     LINE 4, '5\n' '6\n'
     LINE 5, '6\n' '7\n'
     Traceback (most recent call last):

(Note that the recipe doesn't try to catch the StopIteration, but if you 
want that suppressed, it should be a pretty simple change.)


More information about the Python-list mailing list