-1

After completing this task, I realized that it is not being performed correctly since even and odd numbers still remain in the list.How can I fix this error? Or does anyone know how to replace in this case for loop for while loop

  1. Write some code to delete any even numbers from list3
  2. Write some code to delete any odd numbers from list2

list1 = ["\nroll", "burger", "cheese", "ketchup", "mustard"]
list2 = []
list3 = []

a = 0
while a < 10:
 a = a + 1
 userdata = input("Enter a whole number: ")
 usernum = int(userdata)
 list2.append(usernum) 

print (*list1, sep="\n")
list3 = list2.copy()

#remove even
print ("list3",list3)
for i in list3:
    div = i%2
    if div == 0:
        list3.remove(i)
print("remove even, list3",list3)


#remove odd
for x in list2:
    div = x%2
    if div != 0:
        list2.remove(x)
print("remove odd, list2", list2)

tab
  • 25
  • 4

2 Answers2

0

Mutating a list while iterating over it is a big no-no. It may be easier to just recreate it with the items you need:

list2 = [x for x in list2 if x % 2 == 0]
list3 = [x for x in list3 if x % 2 != 0]
Mureinik
  • 297,002
  • 52
  • 306
  • 350
0

You should use list comprehensions:

list3_cleaned = [x for x in list3 if x % 2 != 0]
list2_cleaned = [x for x in list2 if x % 2 == 0]

This way you don't edit a list while iterating over it.

DataJanitor
  • 1,276
  • 1
  • 8
  • 19