Memory allocation in for loops

Scott David Daniels scott.daniels at acm.org
Sun Feb 26 20:54:09 EST 2006


invitro81 wrote:
> Which one is better w.r.t. memory allocation but also w.r.t. speed:
> ## 1.1 ##
> def forloop(a,b):
>     for idx in range(a,b):
>         ...
Above preferred to next (for readability) using xrange may help speed 
depending.

> ## 1.2 ##
> def whileloop(a,b):
>     idx = a
>     while idx < b:
>         ...
>         idx += 1

> def forloop(a,b,lst):
>     for idx in lst.sort():
>         ...
This one just doesn't work.  the sort method on a list causes a
side-effect of sorting the list, and then returns None to remind you.

   def forloop(a,b,lst):
       lst = list(lst) # if you don't want to mangle the original)
       lst.sort()
       for idx in lst:
           ...

With the new-fangled (2.4 or greater) Python, you could use sorted:
   def forloop(a,b,lst):
       for idx in sorted(lst):
           ...

Your other questions were correctly answered elsewhere


--Scott David Daniels
scott.daniels at acm.org



More information about the Python-list mailing list