I see that I can append to a list while iterating over it
lst = [1]
for i in lst:
lst.append(i+1)
print(i)
Am I allowed to make use of this behavior? or is it discouraged? I note that the same can not be said for set
lst = set([1])
for i in lst:
lst.add(i+1)
print(i)
Error: size changed during iteration.
Appending to a list while iterating over it is allowed because lists are ordered so the behavior of appending during iteration is predictable. This makes it useful for retrying failing tasks when all the other tasks in the queue have finished, for example:
tasks = ['task1', 'task2']
for task in tasks:
if task == 'task1':
tasks.append('task1-retry')
print(task)
This outputs:
task1
task2
task1-retry
But sets are not ordered, so adding an item to a set while iterating over it sequentially has an indeterminate effect, and is therefore disallowed.
I think it will not work because, if list size changed then(?) loop items should change as well, e.g. it will probably become infinite loop or memory access violation. Better do it that way:
list=[1,2,7,5]
list2=[]
for i in list:
list2.append(i+1)
print(i)
list=list+list2
As others have already said you will create and infinite loop. But you can catch that with the break statement in python: https://docs.python.org/2.0/ref/break.html
But then again if you catch it with a break you could rewrite it into another loop where it stops whenever the condition is fulfilled that you use for the break statement.
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