0

I am new to python and i was just writing a programm to get an input like :

1 2 3 4 5 6 7 8 9

I wanted to remove the integers which are bigger than 2 and this was my code:

a = input()
b =a.split()

for i in range(len(b)):
    b[i] = int(b[i])    

for i in b:
    if i >=3:
        b.remove(i)

print(b)        

I expected an output like this :

[1,2]

but when I run it,it shows this :

[1, 2, 4, 6, 8]

Can someone tell me ,where I made mistake?

Brave120
  • 11
  • 1
  • In your loop, you are removing the items but your loop will execute exact len(b) times. When you are removing an item from your list, list will shift one position to left. Hence skipping one element. That's why you are getting output as [1,2,4,6,8]. – TheSohan Jul 21 '20 at 18:10

1 Answers1

0

Check with below code:

#a = '1 2 3 4 5 6 7 8 9'
a = input()
b =a.split()

for i in range(len(b)):
    b[i] = int(b[i])    
tempB = [] 
for i in b:
    if i < 3:
        tempB.append(i)

print(tempB)   

More optimized and shortcode:

b =list(map(int,input().split()))
tempB = [i for i in b if i < 3]
print(tempB) 
Ashish Karn
  • 1,127
  • 1
  • 9
  • 20