Skip to content

Instantly share code, notes, and snippets.

@matthewcornell
Created November 20, 2012 15:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save matthewcornell/4118588 to your computer and use it in GitHub Desktop.
Save matthewcornell/4118588 to your computer and use it in GitHub Desktop.
python list cycle alternatives
# current:
def __init__(self, listVals):
self.listVals = listVals
self.currentIndex = -1
def sample(self, ignoredValue):
self.currentIndex = self.currentIndex + 1 if self.currentIndex < len(self.listVals) - 1 else 0
return self.listVals[self.currentIndex]
# % variation:
def sample(self, ignoredValue):
self.currentIndex = (self.currentIndex + 1) % len(self.listVals)
return self.listVals[self.currentIndex]
# itertools.cycle variation:
def __init__(self, listVals):
self.listValsCycle = itertools.cycle(listVals)
def sample(self, ignoredValue):
return next(self.listValsCycle)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment