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.
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다