简体   繁体   中英

Why does this goes on an infinite loop? newbie here

I am new here so I hope I can get some help. So can anyone explain to me how does this become an infinite loop?

def main():  
    myList = ["abc", "de", "f"]  
    for element in myList:  
        print(element)  
        myList.append(element)  
        print("End")   
        print(myList)  
main()  

Because you're mutating myList , the list you're iterating over, while you iterate over it, by keeping appending element to it, so it keeps growing at the same pace you're consuming it, so to speak.

You should iterate over a copy of myList instead:

Change:

for element in myList:

to:

for element in myList[:]:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM