for or while loop to do something n times
Solution 1:
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))
.
Solution 2:
This is lighter weight than xrange
(and the while loop) since it doesn't even need to create the int
objects. It also works equally well in Python2 and Python3
from itertools import repeat
for i in repeat(None, 10):
do_sth()