Is it possible to get index of the next item from iterator?

586 Views Asked by At

Consider the following program, from the title which should be self explanatory . I need to implement the function next_index(it) that returns the index of next item an iterator is about to return.

def next_index(it):
    #do something here
    #return the index of next element the iterator will fetch
    return -1 #dummy value being returned now

l = [0,1,2,3,4]
it = iter(l)
fst = it.__next__()
print(fst) # prints 0, the next call to it.__next__() will return the element at index 1

n_i = next_index(it)
#n_i should be 1
print(n_i)

_ = it.__next__()

n_i = next_index(it)
#n_i should be 2 now
print(n_i)

I know that iterators are typically used when you do not need the index and for index we can use enumerate. However, I am trying to do some dynamic analysis with bytecode level tracing. Loops like the following are iterated using iterators. I need to track the index being accessed by the iterator. Though there should be workarounds, e.g., keeping track of the index in the analysis prgroam explicitely, a function like next_index(it) would make it easy and less error-prone.

l = [0,1,2,3,4]
for c in l:
    print(c)
1

There are 1 best solutions below

0
chepner On

Wrap the iterator with something that keeps count of what's been yielded.

class EnumeratedIter:
    def __init__(self, it):
        self.it = it
        self.index = 0

    def __next__(self):
        self.index += 1
        return next(self.it)

    def __iter__(self):
        return self


def next_index(it):
    return it.index

l = list("abcde")
it = EnumeratedIter(iter(l))

n_i = next_index(it)
assert n_i == 0

next(it)
n_i = next_index(it)
assert n_i == 1

next(it)
n_i = next_index(it)
assert n_i == 2