Possible Duplicate:
Python: Adding element to list while iterating
This doesn't seem to work, but I am not sure why:
for n in poss:
poss.append(n+6)
Is there some rule that says I can't append items to a list that I am currently looping through?
Appending to the list while iterating through it will enter an infinite loop, since you are adding more elements to the loop in each iteration.
You should iterate on a copy of the list instead. For example, try the following:
for n in tuple(poss):
poss.append(n+6)
Your code actually works, but never ends because poss is continously growing.
Try:
poss = [1,2]
for n in poss:
poss.append(n+6)
if n > 10:
print poss
break
produces:
[1, 2, 7, 8, 13, 14, 19]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With