May I loop over a changing list?
Olaf Delgado
delgado at Mathematik.Uni-Bielefeld.DE
Wed Sep 22 08:54:21 EDT 1999
Hi folks!
I am whondering whether the following is considered good (and,
more important: save) programming style in python:
>>> def countdown(n):
... a = [ n ]
... for x in a:
... if x > 0:
... a.append(x-1)
... return a
...
>>> countdown(10)
[10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
If my understanding of what 'for x in y' is meant to do is correct, the
for loop should be equivalent to something like
i = 0
while i < len(a):
x = a[i]
if x > 0:
a.append(x-1)
i = i+1
I think appending to a list while looping over it is a neat way to emulate
a simple queue. The actual example is not quite clever, of course. I
actually use similar pieces of code for doing breadth-first traversals of
graphs.
Cheers,
Olaf
More information about the Python-list
mailing list