Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I append items to a list that I am looping through in Python? [duplicate]

Tags:

python

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?

like image 439
startuprob Avatar asked Oct 21 '25 05:10

startuprob


2 Answers

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)
like image 71
Sujoy Gupta Avatar answered Oct 23 '25 22:10

Sujoy Gupta


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]
like image 20
joaquin Avatar answered Oct 23 '25 22:10

joaquin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!