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

rahul

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.

blhsing

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] 삭제

에서 수정
0

몇 마디 만하겠습니다

0리뷰
로그인참여 후 검토

관련 기사

Clojure Iterating over a list of hash maps

check for multiple substring match in a list while iterating list

Problems with iterating over a string

An exception occurred while iterating over the results of a query for context type 'Volo.Saas.EntityFrameworkCore.SaasDbContext

How to append a list after looping over a dataframe column?

Extracting a single file from a zip archive without iterating over the entire name list in Python

How to iterate through a list and while iterating, iterate through another list and replace values for upper list with inner list key value pairs

Iterating over an array cast as void*

Iterating over hash prints hash?

Iterating over types in a variadic template

Garbage collecting a list while running an IO action over it

Iterating through a list of a class

Iterating through subelements of a list

Iterating over an array of hashes inside of a hash

Iterating over object to see if identical values are found

Iterating over glob patterns, not the files in them

Iterating over form elements array in React

Iterating a generic list with super keyword

Iterating through a list and querying a value

Django template not iterating through list

Python - Error , iterating list of dictionaries

How does the append function of a linked list update a nested node while overwriting the tail?

return false or true while iterating an array of object

Python Linked List Append

list.append 比 np.append 快?

How to append the div at correct place in this case

D3 iterating over selected JSON columns

segfault when iterating over 2d array

Multiple operations iterating over dataframe columns (apply function?)

TOP 리스트

뜨겁다태그

보관