简体   繁体   中英

For loop running infinite python

It's been 5 hours trying to find the issue but unable to identify why for loop for fn in L running infinite.

L=[]
N=int(raw_input())
for i in range(0,N):
    L.append(list(raw_input().split()))
print L

for fn in L:
    if 'insert'==fn[0]:
        L.insert(int(fn[1]),int(fn[2]))
    elif 'append'==fn[0]:
        L.append(int(fn[1]))
    elif 'remove'==fn[0]:
        L.remove(int(fn[1]))
    elif 'pop'==fn[0]:
        L.pop(int(fn[1]))
    elif 'index'==fn[0]:
        L.index(int(fn[1])) 
    elif 'count'==fn[0]:
        L.count(int(fn[1]))
    elif 'sort'==fn[0]:
        L.sort()     
    elif 'reverse'==fn[0]:
        L.reverse() 
    else :
        print  L

Inputs provided to list:

12
insert 0 5
insert 1 10
insert 0 6
print 
remove 6
append 9
append 1
sort 
print
pop
reverse
print

You're mutating your list in the loop. Outcomes will be very unpredictable. You can instead iterate on a slice of the list:

for fn in L[:]:
    # your code here
    pass

In this way, the loop terminates when the items in the shallow copy (the slice) are exhausted.

You insert/remove elements while iterating the elements of a list. You also change the list by reversing the list. Both are mutation operations to the list which are not allowed during iteration. The behavior is unspecified in this case.

for fn in L:
    if ...:
        L.insert(...)

You mutate the object used for looping ... and better you reverse it :p reverse <-- reverse --> reverse <-- reverse -->

:p

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