Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Need to add an element at the start of an iterator in python

I have a program as follows:

a=reader.next()
if *some condition holds*:
    #Do some processing and continue the iteration
else:
    #Append the variable a back to the iterator
    #That is nullify the operation *a=reader.next()*

How do I add an element to the start of the iterator? (Or is there an easier way to do this?)

EDIT: OK let me put it this way. I need the next element in an iterator without removing it. How do I do this>?

like image 365
Goutham Avatar asked Aug 12 '09 05:08

Goutham


1 Answers

You're looking for itertools.chain:

import itertools

values = iter([1,2,3])  # the iterator
value = 0  # the value to prepend to the iterator

together = itertools.chain([value], values)  # there it is

list(together)
# -> [0, 1, 2, 3]
like image 165
kolypto Avatar answered Nov 15 '22 13:11

kolypto