0

Using Python to create a program like below.

If the value in the list is more than 100, the number in the list disappears using the "remove function."

(Example: [37, 66, 88, 111, 245, 33] -> [37, 66, 88, 33])

As you can see from the code that I made at the bottom, Of the values above 100, only one value disappears. It seems that more than one value is not recognized.

lst=[37, 66, 88, 111, 245, 33];

for n in lst:
     if n>100:
          lst.remove(n)

print(lst)

#[37, 66, 88, 245, 33]

Let me know what I did wrong. Even a small hint is fine. It would be very grateful if you let me know.

Mortz
  • 4,654
  • 1
  • 19
  • 35
hdhdd
  • 17
  • 3
  • 1
    Does this answer your question? [How to remove list elements in a for loop in Python?](https://stackoverflow.com/questions/10665591/how-to-remove-list-elements-in-a-for-loop-in-python) In short, don't remove items in a `for` loop. – j1-lee Nov 08 '21 at 07:18
  • It is not a good idea to modify a list that you are iterating over - see here https://stackoverflow.com/questions/1637807/modifying-list-while-iterating – Mortz Nov 08 '21 at 07:22
  • 1
    That's a great question. Even if the answer is already posted, if you don't know the answer, you probably won't find it. instead of modifying your original list, create a new list at the start `new_lst = []` and then instead of removing bad ones from the old list, add good ones to the new list `if n <= 100: new_lst.append(n)` and then print the new list instead. it gets confused when you are modifying something and looping through it at the same time. so would you! – Alex028502 Nov 08 '21 at 07:28

0 Answers0