You can wrap the generator in a generator that generates a sequence of pairs, the first element of which is logical, indicating whether the element is the last but one:
def ending(generator): z2 = generator.next() z1 = generator.next() for x in generator: yield (False, z2) z2, z1 = z1, x yield (True, z2) yield (False, z1)
Let me test it on a simple iterator:
>>> g = iter('abcd') >>> g <iterator object at 0x9925b0>
You should receive:
>>> for is_last_but_one, char in ending(g): ... if is_last_but_one: ... print "The last but one is", char ... The last but one is c
Too what happens under the hood:
>>> g = iter('abcd') >>> for x in ending(g): ... print x ... (False, 'a') (False, 'b') (True, 'c') (False, 'd')
source share