-2

My current code uses a for loop and I'm trying to remove even numbers from list 3 and odd numbers from list 2. However my problem is, that when the for loop iterates, the item in position 2, moves down to position one after an item is removed, therefore it skips an item and the code doesn't work as intended

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

for i in list1:
    print(i)
#code to add ten numbers to list2
a = 0
while a < 10:
 a = a + 1
 userdata = input("Enter a whole number: ")
 usernum = int(userdata)
 list2.append(usernum)

list3[:0]=list2
print(list3)

for n in list2:
     if int(n) % 2 != 0:
         list2.remove(n)
print(list2)

for x in list3:
    if int(x) % 2 == 0:
        list3.remove(x)
print(list3)

How would I make this code remove even and odd using a for loop without skipping any numbers?

Xrin
  • 87
  • 1
  • 3
  • 15

5 Answers5

2

First, you shouldn't modify the list you are iterating over.

As for your problem of removing odd and even number from lists, there is a very simple way for this in Python: filter()

The filter generator combined with a simple lambda function will do the trick:

list3 = filter(lambda x: x % 2, list3)
Maciek
  • 3,174
  • 1
  • 22
  • 26
1

First of all, modifiying a list you are iterating over is an undefined behaviour and so a bad practice. For your problem I would suggest you to use filter:

even = filter(lambda x: x%2, list3)
odd = filter(lambda x: not x%2, list2)
Netwave
  • 40,134
  • 6
  • 50
  • 93
1

Basically modifying your list while iterating is a bad practice. Since the list is being modifed while you are iterating over it. You can use list comprehension:

list2 = [n for n in list2 if int(n) % 2 == 0]
print list2

list3 = [n for n in list3 if int(n) % 2 != 0]
print list3
JRodDynamite
  • 12,325
  • 5
  • 43
  • 63
1

As an alternative to the list filtering, you can sort the values as the user inputs them. With a proper separation of concerns that could look like this:

def get_numbers(num=10):
    for _ in xrange(10):
        yield int(input("Enter a whole number: "))

def populate_lists(size, evens, odds):
    for number in get_numbers(size):
        (odds if (size % 2) else evens).append(number)
bereal
  • 32,519
  • 6
  • 58
  • 104
0

You can copy the list while iterating but do the removal on the actual list:

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

for i in list1:
    print(i)
#code to add ten numbers to list2
a = 0
while a < 10:
 a = a + 1
 userdata = input("Enter a whole number: ")
 usernum = int(userdata)
 list2.append(usernum)

list3[:0]=list2
print(list3)

for n in list(list2):
     if int(n) % 2 != 0:
         list2.remove(n)
print(list2)

for x in list(list3):
    if int(x) % 2 == 0:
        list3.remove(x)
print(list3)
Avihoo Mamka
  • 4,656
  • 3
  • 31
  • 44