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 """
""" % (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 """
""" % (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.