Home > Net >  For loop passes list with step: 2, but i didn`t want it
For loop passes list with step: 2, but i didn`t want it

Time:07-22

a = [1,2,3,4,5]
for i in a:
  print(i) # returns 1,3,5
  if i < 5:
    a.remove(i)
print(a) # returns [2,4,5]

Just for example. This code is used in codewars solution.

CodePudding user response:

a = [1,2,3,4,5]
for i in a:
  print(i) # returns 1,3,5
  if i < 5:
    a.remove(i)
print(a) # returns [2,4,5]

The issue here is for loop is going through index.

   Iteration 1:a=[1,2,3,4,5]
    index =0
    i=1
    while you are doing a.remove will remove 1 and list will have [2,3,4,5]
    
    Iteration 2:a=[2,3,4,5]
    index=1
    i=3
    2 will be skipped as it is in index 0 now.

which is giving the result such a way

CodePudding user response:

If you change your for loop iterator, it will work as expected. So for i in range(1, 5) (or for i in range(1, len(a)) if you need to reference a) instead of for i in a - it's because you are changing the list while iterating through it.

  • Related