goodvibration goodvibration - 2 months ago 9
Python Question

Does "for / range" consume a lot of memory when the range is large?

My concern is with regards to something like:

for i in range(1000000000):
...


From a naive point of view, I assume that an array of 1000000000 integers is allocated and initialized before the loop begins, and deallocated only after the loop ends.

So I am wondering whether or not I should replace it with:

i = 0
while i < 1000000000:
...
i += 1


But according to this answer, a
for
loop is executed faster than the equivalent
while
loop.

So do I have to settle for this kind of trade-off, or is my assumption above wrong, and there is no significant memory impact when iterating a large
range
?

Answer Source

Yes, in python-2.x range will create the whole list.

But you don't necessarily need a while loop you can also use the lazy-range-alternative: xrange.

for i in xrange(1000000000):
    ...