0

I have this below code written to remove numbers greater than 5 from the list. But it does not work though the code looks fine to me. I'm new to python and trying to get my basics right. I decided to use remove since i'm checking based on the value

a = [1,5,4,6,3,8,9,5,9] 
for i in a:
    print (i)
    if i<=5:
        continue
    a.remove(i)
print (a)

Result - [1, 5, 4, 3, 5, 9]

martineau
  • 119,623
  • 25
  • 170
  • 301
Py_learner
  • 53
  • 8

1 Answers1

0

it will not work because you are removing item from list while iterating the same one....so when you remove an element, next iteration you will jump one one them.

Solution: 1) use 2 array; 2) use a while loop and when you remove an element you decrease the len of the array and you don't increment the iteration

a = [1,5,4,6,3,8,9,5,9]
i=0
l=len(a)
while i<l:
    if a[i]>5:
        a.pop(i)
        l-=1
    else:
        i+=1
print (a)

Result:

[1, 5, 4, 3, 5]
Carlo 1585
  • 1,455
  • 1
  • 22
  • 40