Python 'for' loop is memory inefficient
python at mrabarnett.plus.com
Mon Aug 17 15:01:19 CEST 2009
exarkun at twistedmatrix.com wrote:
> On 02:12 am, pavlovevidence at gmail.com wrote:
>> On Aug 16, 3:35�pm, sturlamolden <sturlamol... at yahoo.no> wrote:
>>> On 16 Aug, 14:57, Dennis Lee Bieber <wlfr... at ix.netcom.com> wrote:
>>> > � � � � Well, the alternative would be to have two keywords for
>>> looping: one
>>> > for your "simple" incrementing integer loop, and another for a loop
>>> > 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.
>> It would be a simple to do if you were writing it for a different
>> langauge was a lot less dynamic than Python is. It'd be quite a
>> complex hack to add it to CPython's compiler while maintaing the
>> current highly dynamic runtime semantics and backwards compatibility,
>> which is a design constraint of Python whether you like it or not.
> In your other message, you said this wasn't a legitimate CPython
> complaint. Here, you say that it would be a "complex hack" to implement
> this in CPython. "complex hack" has negative connotations in my mind.
> This seems contradictory to me.
>> And all this complaining about an issue that can be worked around by
>> xrange instead of range. Sheesh.
> Sure. The specific issue of range vs xrange is quite a small one. There
> is a slightly larger one regarding the flexibility (or relative lack
> thereof) of the CPython runtime, though.
A possible solution would be to make 'range' return an instance of, say,
'RangeList', a subclass of list which would behave like 'list'
externally but create the list of values internally only when needed.
More information about the Python-list