Search code examples
python-3.xcontainerspython-itertools

endless container iterator with backward\forward movement support


Is in standart library container with endless forward/backward movement support, like itertools.cycle? Or how to implement one-liner for it?

Current code (github):

def __init__(self, ...):
    self.__weapons = [Weapon()("Blaster"), Weapon()("Laser"), Weapon()("UM")]
    self.__weapon = self.__weapons[0]
    ...

def next_weapon(self):
    ind = self.__weapons.index(self.__weapon)
    if ind < len(self.__weapons) - 1:
        self.__weapon = self.__weapons[ind+1]
    else:
        self.__weapon = self.__weapons[0]

And almost the same code for prev_weapon method.

I want to iterate on endless container in both directions=)

Thanks in advance,

Paul


Solution

  • I decided that best solution is to extend List.

    class InfList(list):
    """Infinite list container"""
    
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self._index = 0
    
    
    def current(self):
        return self[self._index]
    
    
    def next(self):
        self._index = (self._index + 1) % len(self)
        return self[self._index]
    
    
    def prev(self):
        self._index = (self._index - 1) % len(self)
        return self[self._index]