What's the Pythonic way to do this?

Steven Bethard steven.bethard at gmail.com
Fri Sep 10 16:48:55 EDT 2004


Doug Rosser <da_rosser <at> yahoo.com> writes:
> 
> 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]

Well, if all you want to do is cycle through the elements of a list, I'd 
suggest:

>>> import itertools
>>> itertools.cycle(inputList)

If you're really asking about how to write the class, I might write it like:

>>> class Cycle(object):
...     def __init__(self, lst):
...             self.index = -1
...             self.list = lst
...     def next(self):
...             self.index = (self.index + 1) % len(self.list)
...             return self.list[self.index]

Steve




More information about the Python-list mailing list