Python 'for' loop is memory inefficient

Ethan Furman ethan at stoneleaf.us
Mon Aug 17 18:24:26 CEST 2009


Emmanuel Surleau wrote:
>>Dr. Phillip M. Feldman wrote:
> 
> 
> [snip]
> 
> 
>>>def is_prime(n):
>>>   for j in range(2,n):
>>>      if (n % j) == 0: return False
>>>   return True
>>>
>>>It seems as though Python is actually expanding range(2,n) into a list of
>>>numbers, even though this is incredibly wasteful of memory. There should
>>>be a looping mechanism that generates the index variable values
>>>incrementally as they are needed.
>>
[snip]
 >>
>>I will also observe that if you were to stop programming whatever
>>language you are more familiar with in Python, and start programming
>>Python in Python, you'll have an easier time of it.
> 
> 
> I don't see what's particularly un-Pythonic with this code. Not using xrange() 
> is a mistake, certainly, but it remains clear, easily understandable code 
> which correctly demonstrates the naive algorithm for detecting whether n is a 
> prime. It doesn't call for condescension
> 
[snip]
 >
> Cheers,
> 
> Emm

My comment about programming Python in Python was geared more towards 
the subject line than the actual code, and the biases evident in his 
comments in both this thread and earlier ones.

~Ethan~



More information about the Python-list mailing list