Memory allocation in for loops
Diez B. Roggisch
deets at nospam.web.de
Sun Feb 26 18:01:11 EST 2006
> I mean what I really would like is to have something C++ - like "for
> (int idx = a; idx < b; i++) { .. }" where no internal vector or
> something like that is allocated but only a few op's on registers are
> performed; in the whileloop in python the picture is roughly the same
Use xrange instead - as it is customary for at least python2.1, if not even earlier.
> behind the scenes I guess.. but what about in the forloop? Is python
> smart enough not to generate an internal vector as it does usually for
> lists or do I have to apply some modifications (xrange..)? What happens
> further if I do the following:
>
> ## 2.1 ##
>
> def forloop(a,b,lst):
>
> for idx in lst.sort():
> ## ..
> ## do something
> ## ..
>
> #######
>
> Is the sorting function called in every iteration just to detect that
> (after the first sorting) it is useless comming back to the loop or does
> this happen:
>
> ## 2.2 ##
>
> def forloop(a,b,lst):
>
> lst.sort()
> for idx in lst:
> ## ..
> ## do something
> ## ..
>
> #######
The iterable-expression of a for _ in _: is always only evaluated once.
Diez
More information about the Python-list
mailing list