A neater way to print something every x iterations in Python
Posted on Aug. 11, 2009 by Ben Dickson.
This is an old post from 2009. The content may be outdated or no longer relevant.
This is an old post I wrote, which was originally posted on neverfear.org on Tues, 11th Aug 2009 9:01:49. Archived here for posterity.
There are 4 comments on this post.
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 (archive.org link) :
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 (archive.org link) \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.