Difficulty using Itertools cycle

17,372

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
Share:
17,372
Hayden
Author by

Hayden

Updated on July 15, 2022

Comments

  • Hayden
    Hayden almost 2 years

    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.

  • Hayden
    Hayden over 11 years
    I tried what I did in the edited question but it still isn't working. :S
  • Marcin
    Marcin over 11 years
    -1 how does this take OP beyond what they have in the question?
  • DSM
    DSM over 11 years
    @Marcin: Most of the code in the question is from this answer. Originally it seemed like the OP was constructing a new cycle instance every time, although it's hard to tell from next (itertools.cycle (shape_list)) 1 next (itertools.cycle (shape_list)) 2, whatever that might mean. This answer separated out the generator creation from the getting of the next element, which was a perfectly plausible reading of the OP's problem.
  • Hayden
    Hayden over 11 years
    Unfortunately Mark the code still doesn't work. :( Am I doing something wrong?
  • Mark Tolonen
    Mark Tolonen over 11 years
    @Marcin, the OP has edited his question. As DSM says the original question wasn't clear.
  • richar8086
    richar8086 over 7 years
    g.next() doesn't work in Python 3: AttributeError: 'itertools.cycle' object has no attribute 'next' You need to call next(g)