pythoniterator

How to get the item currently pointed at by iterator without incrementing?


Is there a way to get the item pointed at by an iterator in python without incrementing the iterator itself? For example how would I implement the following with iterators:

looking_for = iter(when_to_change_the_mode)
for l in listA:
    do_something(looking_for.current())
    if l == looking_for.current():
        next(looking_for)

Solution

  • looking_for = iter(when_to_change_the_mode)
    current = next(looking_for)
    for l in listA:
        do_something(current)
        if l == current:
            current = next(looking_for)
    

    Question: What if at the end of the iterator? The next function allows for a default parameter.