0

I have tried to practice python programming after a few months. one of my practice was to write a program which analyse a list and detect two digit numbers and then delete all of them from the list and eventually print the list. when I run the above code, it delete the two digit numbers each other number. here is the link of my screenshot ==> enter image description here

here is the code below,

myNo = [5, 10, 13, 40, 32, 14, 98, 201, 11]

for x in myNo:
    if x > 9 and x < 100:
       print("Detected numbers are", x)
       myNo.remove(x)


print(myNo)

when I delete myNo.remove(x) line, the program will detect all of the two digits numbers correctly but the main part of the program is to delete them. I would really appreciate if someone help me to find my problem. thanks

  • you shouldn't modify (delete or append) the list you are iterating. Make a copy of list and delete elements in it – Tugay Dec 01 '20 at 19:07

3 Answers3

0

It's not a good idea to iterate over the list you're modifying. Create a copy of your list with copy.deepcopy() and modify that list, while iterating over the original list.

abe
  • 957
  • 5
  • 10
0

When you remove an item, you shift the elements of the array over, meaning that your iterator actually skips an element. To fix this, keep an index instead and decrease it when removing an index:

i = 0
while i < len(myNo):
    x = myNo[i]
    if x > 9 and x < 100:
        print("Detected number:", x)
        myNo.pop(i) # pop removes the element at the index
        i -= 1
    i += 1

print(myNo)

Alternatively, filter it with a list comprehension:

filtered = [x in myNo if not (x > 9 and x < 100)]
Aplet123
  • 33,825
  • 1
  • 29
  • 55
0

Here is another possible solution:

myNo = [5, 10, 13, 40, 32, 14, 98, 201, 11]
remove_numbers=[]
for x in myNo:
    if 9 < x < 100:
        print("Detected numbers are", x)
        remove_numbers.append(x)
for y in remove_numbers:
    myNo.remove(y)
print(myNo)

This alters the original list

David
  • 769
  • 1
  • 6
  • 28