Search code examples
pythoncyclepython-itertools

Modify Itertools.cycle()


I'm currently using the itertools.cycle() object, and I was wondering if there was anyway to modify the cycle after it's creation. The following:

my_cycle = itertools.cycle([1,2,3])
print my_cycle.next()
my_cycle.delete()    #function doesn't exist
print my_cycle.next()

would have an output of:

1
3

Is there any way to achieve this through itertools? Or perhaps another object? Or do I need to implement my own object to do this.


Solution

  • Itertools doesn't provide such an option. You can build it with a deque:

    from collections import deque
    
    class ModifiableCycle(object):
        def __init__(self, items=()):
            self.deque = deque(items)
        def __iter__(self):
            return self
        def __next__(self):
            if not self.deque:
                raise StopIteration
            item = self.deque.popleft()
            self.deque.append(item)
            return item
        next = __next__
        def delete_next(self):
            self.deque.popleft()
        def delete_prev(self):
            # Deletes the item just returned.
            # I suspect this will be more useful than the other method.
            self.deque.pop()