Python 'for' loop is memory inefficient

Stefan Behnel stefan_ml at
Mon Aug 17 15:20:31 CEST 2009

Carl Banks wrote:
> On Aug 16, 3:35 pm, sturlamolden <sturlamol... at> wrote:
>> On 16 Aug, 14:57, Dennis Lee Bieber <wlfr... at> wrote:
>>>         Well, the alternative would be to have two keywords for looping: one
>>> for your "simple" incrementing integer loop, and another for a loop that
>>> operates over the elements of some collection type.
>> A compiler could easily recognise a statement like
>>    for i in range(n):
>> as a simple integer loop.
>> In fact, Cython is able to do this.
> Cython can do this easily because it is a different language that is a
> lot less dynamic than Python.

Actually, Cython is able to do this because it knows the global scope of a
module. The only thing that this optimisation makes impossible when you
compile your module using Cython is to inject builtins into the module
namespace *after* the compilation, either by assigning module attributes or
by importing the module into a custom namespace.

Given that both use cases are extremely rare, it was decided that
optimisations like this are more important than the ability to redefine the
most common builtins (such as 'range' or 'enumerate'). So, in a way, Cython
really makes them "builtins".


More information about the Python-list mailing list