Looping using iterators with fractional values
reinhold-birkenfeld-nospam at wolke7.net
Sat Jan 1 16:24:40 EST 2005
Mike Meyer wrote:
> Or - and much safer when dealing with floating point numbers - iterate
> over integers and generate your float values:
> for j in range(1, 9):
> i = j * .25
> print "%9.2f" % i
There's a glitch there, though - should be range(1, 10).
PS: I'm wondering whether my genexp approach or this one is preferable.
Readability is equal, I would say, but how about speed?
Brought up a few timeits:
for i in [x/4.0 for x in range(1, 10)]: 36,9 sec
for j in range(1, 10): i = j * 0.25: 33,7 sec
for i in (x/4.0 for x in range(1, 10)): 32,5 sec
for j in range(1, 10): i = j * 0.25: 28,4 sec
So what does that tell us?
(a) don't use genexps where there is a simpler approach
(b) Py2.4 rocks!
More information about the Python-list