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.

    Published by

    matt

    My name is Matt Wilson. I make websites for Kiwee to pay the bills. I live in Cleveland Heights, Ohio, with my wife and son.

    • http://farmdev.com/ Kumar McMillan

      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.

    • http://hauser.plom.pl hauser

      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)

    • http://www.cruiselinefans.com/ Cruises

      This posting is marvelous and what a fantastic research that you have done. It has helped me a lot. thank you very much.

    • OnealBlocker677

      It's realy nice i posted ur story on my blog

      respect
      jimmy banger
      ______________________________________________
      pass a drug test | how to beat a drug test | beat a drug test

    • http://reenaverma1988.blogspot.com/ Reena Verma

      I digged this for more news from you.

      Thanks
      Reena Verma
      ______________________________________________