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
3
  • What input are you giving it? Commented Jun 9, 2016 at 16:38
  • @mgilson: added input in question Commented Jun 9, 2016 at 16:39
  • Which for loop inside the for loop? I see two not nested explicit for loops. Commented Jun 9, 2016 at 16:40

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for the answer. What is slice of list?
It s a shortcut, a slice ([:]) without bound, so a copy of the list as slicing a list create a new list. stackoverflow.com/questions/509211/…
@Code-Monk In this context: a temporary shallow copy of the original list. Read more here
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(...)

Comments

1

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

:p

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.