0

I am gonna print numbers less than 5, but the answer is not what I mean? how should I solve the problem?

a= [1,2,3,4,5,6,7,8,9]
for b in a:
 if b>=5:
  a.remove(b)      
print(a)

answer:

[1, 2, 3, 4, 6, 8]
DYZ
  • 55,249
  • 10
  • 64
  • 93
aliiyo
  • 1
  • 1
  • 1
    See https://stackoverflow.com/questions/52345424/in-place-modification-of-array-in-python basically don't modify array's that you are iterating over. – scrappedcola Apr 08 '22 at 17:15
  • Does this answer your question? [Strange result when removing item from a list while iterating over it](https://stackoverflow.com/questions/6260089/strange-result-when-removing-item-from-a-list-while-iterating-over-it) – DYZ Apr 08 '22 at 19:16

0 Answers0