Amazon.com Widgets How to use itertools.cycle to set even and odd rows | t+1: Matt Wilson's blog

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 """<li class="%s">%s</li>""" % (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 """<li class="%s">%s</li>""" % (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.

2 Comments »

  1. Kumar McMillan said,

    January 31, 2008 @ 2:53 pm

    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. hauser said,

    January 31, 2008 @ 3:49 pm

    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)

RSS feed for comments on this post · TrackBack URI

Leave a Comment