[triangle-zpug] why is this using a lot of memory?

Philip Semanchuk philip at semanchuk.com
Tue Mar 25 15:52:36 UTC 2008


On Mar 25, 2008, at 11:23 AM, Joseph Mack NA3T wrote:
> intervals=10000000 #some large number
> height=0
> for x in range(0, intervals):
>  	height+=x
>
> (I get the same result whether running interactive or from a
> file with the above code)
>
> For a sufficiently large value of "intervals" the program
> exits immediately with a MemoryError. For slightly smaller
> values, the program takes up most of the memory of the
> machine. I would have thought that you'd only be allocating
> a couple of variables. What am I missing? Am I allocating an
> "intervals" number of something, rather than a single
> variable with a large value?

range() builds a list of numbers in memory, so you're creating a list  
with 10000000 elements. Check out the function xrange() instead.

Cheers
Philip



More information about the triangle-zpug mailing list