Purify


#1

I am confused as to why this code isnt working??

def purify(x):
    for a in x:
        if a % 2 != 0:
            while a in x:
                x.remove(a)
    return (x)

purify([4,1,5,1341,34,6,8])

This returns [4,5,34,6,8]
I dont understand why the 5 is not removed??


#2

This is what I have understood.

This is the list of elements in your list.

1st: 4
2nd: 1
3rd: 5
4th: 34
and so on

1st Run of the for loop:

When the for loop starts to iterate, a will be your 1st element. Now it is even so the if statement is ignored.

2nd Run of the for loop:

Now, in the second run a will be your 2nd element. Now the 2nd element is odd, so the if statement is executed and the 2nd element is removed from the list.

Now your list looks something like this

1st: 4
2nd: 5
3rd: 34
and so on

3rd Run of the for loop:

Now, in the next run, a will be the 3rd element of the list, but as we see the list is now modified and the 3rd element is now not 5 but 34. So in this way, 5 is ignored in the for loop.

Hope, you get the idea.


#3

in short, a list can't have empty indexes, so when you remove 1 from list, everything (at right side) shift to the left while the for loop continues.

this problem can be solved two ways: don't look over the same list as you are removing from.

Traverse the list index in reverse, index shifts do not occur then

append constants to new list

that is 3 possible ways


#4

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.