1

This code removes numbers greater than 2 for a low number of inputs, but when the number of inputs increases, it does not remove numbers greater than 2, I wanted to know the reason ???

code :

x = int(input())
list = []
for i in range(x) :
    m = int(input())
    list.append(m)
for i in list :
    if i > 2 :
        list.remove(i)
print(list)
print(len(list))
z = len(list) / 3
print (int(z))

Entrance : 41 5,3,3,1,1,2,5,0,1,3,1,1,4,2,0,3,1,3,3,4,4,1,2,0,5,3,3,1,0,5,0,1,2,2,1 ,0,2,5,0,4,2

Output : [1, 1, 2, 0, 1, 1, 1, 2, 0, 1, 3, 1, 2, 0, 3, 3, 1, 0, 0, 1, 2, 2, 1, 0, 2, 0, 4, 2] 28 9

  • Don't delete items from a list while you are iterating it. Instead, build a new list with the items that pass. `lst = [i for i in lst if i <= 2]`. And don't name a variable `list`. That conflicts with the built-in type name. – Tim Roberts Apr 29 '21 at 20:18

1 Answers1

0

because remove function remove single element not all from the list.

try it:

x = int(input())
list= []
for i in range(x) :
    m = int(input())
    list.append(m)
while(1):
    flag=1
    for j in list:
        if j>2 :
           list.remove(j)
           flag=0
    if(flag):
        break
print(list) 
Robert
  • 7,394
  • 40
  • 45
  • 64
Akash Kumar
  • 29
  • 1
  • 1
  • 8