26

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)
fakedrake
  • 6,528
  • 8
  • 41
  • 64

4 Answers4

22

Iterators don't have a way to get the current value. If you want that, keep a reference to it yourself, or wrap your iterator to hold onto it for you.

Ned Batchelder
  • 364,293
  • 75
  • 561
  • 662
12
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.

Marco de Wit
  • 2,686
  • 18
  • 22
4

I don't think there's a built-in way. It's pretty easy to just wrap the iterator in question inside a custom iterator that buffers one element.

For example: How to look ahead one element in a Python generator?

Community
  • 1
  • 1
sshannin
  • 2,767
  • 1
  • 22
  • 25
3

When I needed to do this, I solved it by creating class like:

class Iterator:
    def __init__(self, iterator):
        self.iterator = iterator
        self.current = None
    def __next__(self):
        try:
            self.current = next(self.iterator)
        except StopIteration:
            self.current = None
        finally:
            return self.current

This way you're able to use next(itr) just like for standard iterator, and you're able to get current value by calling itr.current.

romanotpd
  • 121
  • 9