I used the idea from the attached possible answers, the redefined code_readerfunction is described below :
def code_reader(code):
length = len(code)
i = 0
while i < length:
val = (yield i)
if val != 'position':
yield code[i]
i += 1
using .send ('position'), I would know the position of the next element to be generated, i.e.
a = code_reader("foobar")
print a.next()
print a.send('position')
print a.next()
print a.send('position')
print a.send('position')
print a.next()
print a.send('position')
output:
0
0
f
1
1
o
2
source
share