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

Discussão em 'Python' iniciado por Stack, Abril 5, 2025.

  1. Stack

    Stack Membro Participativo

    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)

    Continue reading...

Compartilhe esta Página