Home > Net >  For loop does not iteration for whole list
For loop does not iteration for whole list

Time:01-23

myList=[0,1,2,2,3,0,4,2]  
val=2  
for i in myList:  
    if i==val:  
        myList.remove(val)  
print(myList)   

output=[0,1,3,0,4,2] List contain 8 elements but loop is only iterating for 7 times
i only need to modify original list(myList)

CodePudding user response:

I'm having a hard time understanding what your question is, but I'll try to identify some easier way to go about the problem.

Can you just make a new list that contains the new values, instead of removing from the old? For instance:

list = []
myList = [0,1,2,2,3,0,4,2]
for i in myList:
    if i != 2:
        list.append(i)

I think python's getting confused when you remove elements in the middle of a loop like that.

*Side note - to place inline code in stack overflow, put 4 spaces, then the line of code.

CodePudding user response:

If you run your code like this, you can see what's happening. The full list is iterated, however the iteration is satisfied by the last element before the if statement gets evaluated. The output looks like this:

myList [0, 1, 2, 2, 3, 0, 4, 2] i 0
myList [0, 1, 2, 2, 3, 0, 4, 2] i 1
myList [0, 1, 2, 3, 0, 4, 2] i 2
myList [0, 1, 2, 3, 0, 4, 2] i 3
myList [0, 1, 2, 3, 0, 4, 2] i 0
myList [0, 1, 2, 3, 0, 4, 2] i 4
myList [0, 1, 3, 0, 4, 2] i 2 


myList=[0,1,2,2,3,0,4,2]  
val=2  
for i in myList:
    if i==val:  
        myList.remove(val)
    print('myList',myList, 'i', i )
  •  Tags:  
  • Related