Difficulty using Itertools cycle

Hayden picture Hayden · Aug 31, 2012 · Viewed 17k times · Source

At the moment I have defined many shapes in Turtle using begin_poly and end_poly then register_shape. I want to be able to put all of these values into a list and, with a press of a button, cycle through the list hence changing the Turtle shape. I am having difficulty achieving this with Itertools and was wondering for some assistance on how I could achieve this.

Edit: I got it working in the end, I appended all the values into a list then used a counter to choose which index to go to.

Answer

Mark Tolonen picture Mark Tolonen · Aug 31, 2012

First, create the generator:

>>> import itertools
>>> shape_list = ["square", "triangle", "circle", "pentagon", "star", "octagon"]
>>> g = itertools.cycle(shape_list)

Then call next() whenever you want another one.

>>> next(g)
'square'
>>> next(g)
'triangle'
>>> next(g)
'circle'
>>> next(g)
'pentagon'
>>> next(g)
'star'
>>> next(g)
'octagon'
>>> next(g)
'square'
>>> next(g)
'triangle'

Here's a simple program:

import itertools
shape_list = ["square", "triangle", "circle", "pentagon", "star", "octagon"]
g = itertools.cycle(shape_list)
for i in xrange(8):
    shape = next(g)
    print "Drawing",shape

Output:

Drawing square
Drawing triangle
Drawing circle
Drawing pentagon
Drawing star
Drawing octagon
Drawing square
Drawing triangle