Home > Mobile >  What is wrong with my for loop? All odd numbers are not being removed from list
What is wrong with my for loop? All odd numbers are not being removed from list

Time:09-26

def delete_odd(num_list):
    """Removes all odd numbers from a list of numbers.
    Args:
        num_list (list): List of numbers to be checked.
    Returns:
        list: List of numbers with all odd numbers removed.
    """
    new_list = list(num_list)
    for num in new_list:
        if num % 2 == 1:
            new_list.remove(num)
    return new_list

delete_odd([7, 65, 1337, 8, -2, 24, 6, 67, 54, 36, 25, 1, 42, 9, 138, 4356, 6])

when invoked it returns this:

[65, 8, -2, 24, 6, 54, 36, 1, 42, 138, 4356, 6]

I have been working on this for some time now and can't seem to figure it out

CodePudding user response:

The problem here is that you are removing elements while you are looping over the list. So, when you remove the item at index 0 (which is 7), every item in the list will shift its index by -1. So, when the next iteration happens, number 1337 is actually at index 1. A couple of options:

  • Since you are creating a new list anyway and not modifying the original, just initialize a new list and populate it with items that are even:
    new_list = []
    for num in num_list:
        if num % 2 == 0:
            new_list.append(num)
    return new_list
  • You can also loop backwards, to avoid having the issue of shifting elements and modify the original list. I think using del will be preferable since this removes items by index, rather than by value. This will allow you to safely remove duplicate values if they appear.
    for index in range(len(num_list) - 1, -1, -1) :
        if num_list[index] % 2 == 1:
            del num_list[index]
    return num_list

    # using reversed   range:
    for index in reversed(range(len(num_list) - 1)) :
        if num_list[index] % 2 == 1:
            del num_list[index]
    return num_list

CodePudding user response:

The reason why is because when you do .remove() inside a for loop, it will cause some skipping of indices. You can try to make your list full of only odd numbers and you will see there are still many odd numbers in your list remaining.

I think you have to update your new_list every time it comes back to the for loop by using new_list[:], like this:

def delete_odd(num_list):
    new_list = list(num_list)

    for num in new_list[:]:
        if num % 2 == 1:
            new_list.remove(num)

    return new_list

CodePudding user response:

you can simply save the odd numbers in other list and delete them later in other for loop:

def delete_odd(num_list):
    new_list = list(num_list)
    oddNums  = []
    for num in new_list:
        if num % 2 == 1:
            oddNums.append(num)
    for oddnum in oddNums:
        new_list.remove(oddnum)

    return new_list

print(delete_odd([7, 65, 1337, 8, -2, 24, 6, 67, 54, 36, 25, 1, 42, 9, 138, 4356, 6]))
  • Related