Reputation: 59
Just trying to do something like this. I want to keep appending to lst, and keep iterating over what was added.
lst = [secondLst]
for i in lst:
*some code*
lst.append(x)
And i would eventually reach x in the for loop.
Is this possible? Is there a better way?
Upvotes: 4
Views: 467
Reputation: 70602
Yes, it works fine. Internally, Python maintains a list index, increments it by 1 on each iteration, and checks it anew against the then-current length of the list each time. The list length is not captured at the very start of the loop. So, for example:
>>> L = [10, 20, 30]
>>> for i, v in enumerate(L):
... print(v)
... if i < 3:
... L.append(i)
10
20
30
0
1
2
It may be clearer to do it more explicitly, though. For example:
>>> import itertools
>>> L = [10, 20, 30]
>>> extras = []
>>> for i, v in enumerate(itertools.chain(L, extras)):
... print(v)
... if i < 3:
... extras.append(i)
You can read the docs:
Note: There is a subtlety when the sequence is being modified by the loop (this can only occur for mutable sequences, i.e. lists). An internal counter is used to keep track of which item is used next, and this is incremented on each iteration. When this counter has reached the length of the sequence the loop terminates. This means that if the suite deletes the current (or a previous) item from the sequence, the next item will be skipped (since it gets the index of the current item which has already been treated). Likewise, if the suite inserts an item in the sequence before the current item, the current item will be treated again the next time through the loop.
Upvotes: 3