for or while loop to do something n times

Sventimir picture Sventimir · Jul 15, 2013 · Viewed 103.4k times · Source

In Python you have two fine ways to repeat some action more than once. One of them is while loop and the other - for loop. So let's have a look on two simple pieces of code:

for i in range(n):
    do_sth()

And the other:

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

My question is which of them is better. Of course, the first one, which is very common in documentation examples and various pieces of code you could find around the Internet, is much more elegant and shorter, but on the other hand it creates a completely useless list of integers just to loop over them. Isn't it a waste of memory, especially as far as big numbers of iterations are concerned?

So what do you think, which way is better?

Answer

Amber picture Amber · Jul 15, 2013

but on the other hand it creates a completely useless list of integers just to loop over them. Isn't it a waste of memory, especially as far as big numbers of iterations are concerned?

That is what xrange(n) is for. It avoids creating a list of numbers, and instead just provides an iterator object.

In Python 3, xrange() was renamed to range() - if you want a list, you have to specifically request it via list(range(n)).