how best to iterate i times ?

Randall Smith randall at tnr.cc
Wed Mar 17 20:07:36 CET 2004


In the case I know how may times I want to iterate, one way to do it is 
like this:

for i in range(100000):
	dothis()

I like how clean this syntax is, but this method is very wasteful.  The 
list created by range(100000) consumes a fair amount of memory and it is 
only used to iterate.

This uses less memory:

i = 0
while i <= 100000:
	dothis()
	i = i + 1
del i

The problem with the while loop is that it is ugly.  I have to introduce 
a new variable i, and assign a new value every time I loop.  Also, any 
links I may have to i, say (y = i) will break when I reassign with (i = 
i + 1) rather than y continuing to = i.

Example
i = 0
y = i
while i <= 100000:
	dothis()
	i = i + 1

print i # i == 100001
print y # y == 0

There are times when I need to know the state of an 'iterator'.

So, question is:  What is the efficient, elegant, pythonic way to 
iterate with integers?

Randall



More information about the Python-list mailing list