Python 'for' loop is memory inefficient

Emmanuel Surleau emmanuel.surleau at
Sun Aug 16 08:30:54 CEST 2009

> Dr. Phillip M. Feldman wrote:


> > 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.
> You already have an answer to the range issue, so I will only add that
> putting a loop inside another loop is a decent way to expand the time
> taken.
> 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

> The Dive Into Python is an excellent start for that.

I never read it, but I was under the impression that the tutorial on was geared toward programmers moving to Python from other 
languages. It was also my impression that Dive Into Python is rather outdated 
and occasionally inaccurate (based on comments on this mailing list).



More information about the Python-list mailing list