Python 'for' loop is memory inefficient
Emmanuel Surleau
emmanuel.surleau at gmail.com
Sun Aug 16 09:34:06 EDT 2009
> 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.)
Fair enough. But as far as I know, for i in (x)range(num) is the canonical way
to iterate over numbers in Python.
Another case of lack of RTFM* before answering, I suppose.
Cheers,
Emm
*Read The Fine Mail
More information about the Python-list
mailing list