A neater way to print something every x iterations in Python

ben
Mon, 10 Aug 2009 23:31:49 +0000

To print some information every 10 loop iterations can be a bit messy. Given the following, simple loop:

for x in lots_of_stuff:
    process(x)

The "dumbest" way would be:

i = 0
for x in lots_of_stuff:
    process(x)
    if i % 10 == 0:
        print "Some progress info"
    i += 1

A more elegant solution would be to use the enumerate built-in:

for i, x in enumerate(lots_of_stuff):
    process(x)
    if i % 20 == 0:
        print "Some progress info"

Much nicer, but this doesn't work with while loops, such as the following:

while True:
    process_something()

In such cases, we would be back to "old", disturbingly-C-like way..

i = 0
while 1:
    process_something()
    if i % 20 == 0:
        print "Some progress info"
    i += 1

...unless we use.. generators \o/

First, we make a simple generator function:

def alternator(num):
    i = 0
    while 1:
        yield i % num == 0
        i += 1

Then set it up before the while loop, and use it:

x = alternator(20)
while 1:
    process_something()
    if x.next():
        print "Some progress info"

Okay, it's not hugely neater, but at least the counting/modulo stuff is outside the loop.