[Tutor] while statement

Jeff Shannon jeff@ccvcorp.com
Fri May 2 13:38:02 2003


Sean 'Shaleh' Perry wrote:

>>for n in range(1, N+1):
>>    do_stuff
>>
>>range(x, y) creates a list with the integer elements i, where x <= i < y,
>>and the for loop will iterate through each element in this list,
>>assigning the current element to n.
>>
>
>I personally find this horribly wasteful.  xrange() at least generates the 
>next element when it is needed.
>
>range(1,100) # builds a 100 item list, ick.
>
>Sure this is a scripting language, but no need to waste cycles uselessly.
>

As I understand it, range() and xrange() represent a speed/memory 
tradeoff.  xrange() has a higher setup cost than range() does (at least, 
for small ranges), so that in common cases range() may represent less 
cycles.  (There are also situations where it's advantageous to have a 
fully-realized list, as well.)  And in most cases, a list of a few 
hundred items *is* relatively insignificant to build, so worrying about 
range() vs xrange() strikes me as being premature optimization until 
we've determined that there's a notable bottleneck.

Jeff Shannon
Technician/Programmer
Credit International