1

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
Abhishek Ginani
  • 4,511
  • 4
  • 23
  • 35

3 Answers3

7

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.

Moses Koledoye
  • 77,341
  • 8
  • 133
  • 139
  • Thanks for the answer. What is slice of list? – Abhishek Ginani Jun 09 '16 at 16:44
  • It s a shortcut, a slice ([:]) without bound, so a copy of the list as slicing a list create a new list. https://stackoverflow.com/questions/509211/explain-pythons-slice-notation – Khertan Jun 09 '16 at 16:47
  • @Code-Monk In this context: a temporary shallow copy of the original list. Read more [here](https://ramisayar.com/hidden-features-in-python-slicing-and-sliding/) – Moses Koledoye Jun 09 '16 at 16:49
2

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(...)
Matthias
  • 4,481
  • 12
  • 45
  • 84
1

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

:p

Khertan
  • 93
  • 7