What's the Pythonic way to do this?

Aahz aahz at pythoncraft.com
Fri Sep 10 20:22:47 EDT 2004


In article <qcOdnYlYFO0Wjt_cRVn-tQ at powergate.ca>,
Peter Hansen  <peter at engcorp.com> wrote:
>Doug Rosser wrote:
>> class Cycle(object):
>> 
>>     def __init__(self, inputList):
>>         object.__init__(self)
>>         self.index = 0
>>         self.limit = len(inputList)
>>         self.list = inputList
>> 
>>     def next(self):
>>         """
>>         returns the next element of self.list, jumping
>>         back to the head of the list if needed.
>>         Yes, this is an infinite loop. (Use with caution)
>>         Arguments:
>>             none
>>         Returns:
>>             the next element of self.list
>>         """
>>         if self.index+1 < self.limit:
>>             self.index+=1
>>             return self.list[self.index-1]
>>         else:
>>             self.index=0
>>             return self.list[self.limit-1]
>
>I think this is spelled like this now:
>
>import itertools
>mycycle = itertools.cycle(inputList)

That doesn't appear to work if self.list gets mutated.  Then again, the
OP's version doesn't work, either.  I'd use a linked list myself.
-- 
Aahz (aahz at pythoncraft.com)           <*>         http://www.pythoncraft.com/

"A foolish consistency is the hobgoblin of little minds, adored by little
statesmen and philosophers and divines."  --Ralph Waldo Emerson



More information about the Python-list mailing list