Python 'for' loop is memory inefficient
Steven D'Aprano
steve at REMOVE-THIS-cybersource.com.au
Sun Aug 16 04:32:35 EDT 2009
On Sun, 16 Aug 2009 08:30:54 +0200, Emmanuel Surleau wrote:
[...]
>> I will also observe that if you were to stop programming whatever
>> language you are more familiar with in Python, and start programming
>> Python in Python, you'll have an easier time of it.
>
> I don't see what's particularly un-Pythonic with this code. Not using
> xrange() is a mistake, certainly, but it remains clear, easily
> understandable code which correctly demonstrates the naive algorithm for
> detecting whether n is a prime. It doesn't call for condescension
It's a particular unfair criticism because the critic (Ethan Furman)
appears to have made a knee-jerk reaction. The "some language in Python"
behaviour he's reacting to is the common idiom:
for i in range(len(seq)):
do_something_with(seq[i])
instead of the "Python in Python" idiom:
for obj in seq:
do_something_with(obj)
That's a reasonable criticism, but *not in the case*. Ethan appears to
have made the knee-jerk reaction "for i in range() is Bad" without
stopping to think about what this specific piece of code is actually
doing.
(Replace 'obj' with 'j', 'seq' with 'range(2, n)', and
'do_something_with' with 'if (n % j) == 0: return False', and you have
the exact same code pattern.)
--
Steven
More information about the Python-list
mailing list