Python 'for' loop is memory inefficient

MRAB python at mrabarnett.plus.com
Sun Aug 16 22:00:27 CEST 2009


bartc wrote:
> 
> "Steven D'Aprano" <steve at REMOVE-THIS-cybersource.com.au> wrote in 
> message news:02969972$0$20647$c3e8da3 at news.astraweb.com...
>> On Fri, 14 Aug 2009 18:25:45 -0700, Dr. Phillip M. Feldman wrote:
>>
>>> 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.
>>
>>
>> Others have already pointed out to you that xrange() (for Python 2.x)
>> does what you want. In Python 3.x, the old range() is gone for good, and
>> xrange() renamed to just range().
> 
> It does seem rather worrying that whoever originally thought up Python 
> decided it would be a good idea to implement a simple 1 to N (or 0 to 
> N-1) for-loop by first creating an array of N consecutive integers!
> 
Whoever? I am shocked! ;-)

> They must have known Python was going to be slow anyway, but this 
> wouldn't have helped the speed any. Nor the memory consumption.
> 
> A for-loop, for iterating over a simple sequence, should be one of the 
> fastest things in the language.
> 
> [Presumably the internal code that created those consecutive integers 
> used a more conventional looping method...]
> 




More information about the Python-list mailing list