4

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?

Community
  • 1
  • 1
startuprob
  • 1,917
  • 5
  • 30
  • 45
  • Need to use a copy. Use a slice: `poss[::]` a tuple: `tuple(poss)` or a duplicate list: `list(poss)` which is the same as the slice form... – the wolf May 09 '11 at 00:24

2 Answers2

3

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)
Sujoy Gupta
  • 1,424
  • 1
  • 10
  • 12
3

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]
joaquin
  • 82,968
  • 29
  • 138
  • 152