How to use itertools.cycle to set even and odd rows

I find code like this in a lot of web applications:

list_of_x_objects = ['a', 'b', 'c', 'd', 'e']
for i, x in enumerate(list_of_x_objects):
if i % 2: htmlclass = "odd"
else: htmlclass = "even"
print """

  • %s
  • """ % (htmlclass, x)

    Never mind the print statement. That’s just to illustrate the point without having to explain some template syntax.

    The same thing can be expressed with itertools.cycle:

    list_of_x_objects = ['a', 'b', 'c', 'd', 'e']
    for htmlclass, x in zip(itertools.cycle(['odd', 'even']), list_of_x_objects):
    print """

  • %s
  • """ % (htmlclass, x)

    I see several advantages of the second approach:

    • It’s way more flexible. I can easily switch to a style that repeats every three lines (or four, or five…).
    • I don’t create the variable i when all I really want is a class variable that toggles between values.
    • The second approach avoids the modulus operator. Since I hardly ever use the modulus operator, when I do come across it, I always have to take a second and puzzle out what’s happening.

    5 thoughts on “How to use itertools.cycle to set even and odd rows

    1. nice. Modulus is typically a slow operation, as well. Not that I’ve benchmarked any of this … quite likely that some kind soul has optimized it in python.

    2. Modulus operator is not so bad 🙂 You could use also:

      list_of_x_objects = ['a', 'b', 'c', 'd', 'e']
      for i, x in enumerate(list_of_x_objects):
      print """%s""" % ( ("odd","even")[i%2], x)

    Comments are closed.