python - for or while loop to do something n times -


in python have 2 fine ways repeat action more once. 1 of them while loop , other - for loop. let's have on 2 simple pieces of code:

for in range(n):     do_sth() 

and other:

i = 0 while < n:     do_sth()     += 1 

my question of them better. of course, first one, common in documentation examples , various pieces of code find around internet, more elegant , shorter, on other hand creates useless list of integers loop on them. isn't waste of memory, far big numbers of iterations concerned?

so think, way better?

but on other hand creates useless list of integers loop on them. isn't waste of memory, far big numbers of iterations concerned?

that xrange(n) for. avoids creating list of numbers, , instead provides iterator object.

in python 3, xrange() renamed range() - if want list, have request via list(range(n)).


Comments