Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it correct to append to a list while iterating over it?

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.

like image 832
Rahul Gopinath Avatar asked Oct 17 '18 10:10

Rahul Gopinath


3 Answers

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.

like image 154
blhsing Avatar answered Sep 27 '22 23:09

blhsing


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
like image 21
BladeMight Avatar answered Sep 27 '22 22:09

BladeMight


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.

like image 28
dhae Avatar answered Sep 27 '22 23:09

dhae