goodvibration goodvibration - 1 year ago 89
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
loop is executed faster than the equivalent

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

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):
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download