xrange questioin

Bengt Richter bokr at oz.net
Sat Jul 27 21:40:25 EDT 2002


On Sat, 27 Jul 2002 23:32:45 GMT, "Fredrik Lundh" <fredrik at pythonware.com> wrote:

>Gerald Squelart wrote:
>
>> Ok, let me rephrase Chris' question for a simpler case:
>> What is better: for x in range(n) or for x in xrange(n)?
>> (with n is relatively small, like 10 or 100)
>
>for in range() is usually a few percent faster, but if you do some-
>thing inside the loop, you'll hardly notice the difference.
>
>if performance matters a lot, I suggest benchmarking.
>
But speed isn't the only thing. Range builds a potentially
huge list in membory. If we didn't have range to seduce us
into wasting memory, we could still do [x for x in xrange(n)]
now that we have list comprehensions. It might be slower than
range(n), of course, unless that case were specially optimized.

Regards,
Bengt Richter



More information about the Python-list mailing list