# 15.12 - purify

#1

<Below this line, add a link to the EXACT exercise that you are stuck at.>
<In what way does your code behave incorrectly? Include ALL error messages.>
My code won’t odd numbers if there are two identical numbers in a row - for example, purify([4,7,7,4]) returns [4,7,4]. purify([4,7,4,7,4]), however, returns [4,4,4]
<What do you expect to happen instead?>

```python

def purify(num):
for n in num:
if n % 2 != 0:
num.remove(n)
return num

``<do not remove the three backticks above>``

#2

two numbers in a row is a problem, here is why:
list = [4,7,7,4]
at index 0: 4
at index 1: 7
at index 2: 7
at index 3: 4
Does that make sense? Now we are going to loop over this list (`for n in num`), as we arrive at index 1, the if statement is true, and the 7 gets removed. But now, things are going to shift. The 7 at index 2 is going to shift to index 1, but the counter of the loop will continue to index 2 (which now holds the number 4), so the 7 which was original at index 2, shifted to index 1, while the loop continued continued to index 2. Which is why it doesn’t get removed

Oops, that is not good. Can we resolve this problem with resolve? The truthful answer is yes, but it becomes so much more difficult/complex.

I suggest to append even numbers to a new lists, that is so much easier

#3

your indexing skips next 7 when the first 7 is removed. Append the numbers in a new list instead of modifying your argument num.

#6

That makes a lot of sense, thank you

#8

I ran into the same problem, thanks for the answer stetim94!

I was trying to use the “remove” function and a new way of copying a list (a = list(b)) to do something a little different than the past few problems. Is there any way to make this work without appending? Here is my code:

``````from random import randint

a = [randint(0, 10), randint(0, 10), randint(0, 10), randint(0, 10), randint(0, 10)]

def purify(sequence):
sequence_2 = list(sequence)
for item in sequence_2:
if item % 2 != 0:
sequence_2.remove(item)
return sequence_2

print a
print purify(a)
``````

#9

def purify(num):
for i in num:
new =
if i % 2 == 0:
new.append(i)
return new

thats my code and it doesnt work

#10

new = before for loop instead of inside for loop should solve it

#11

tried it and it still gave me this error Oops, try again.
Your function fails on purify([4, 5, 5, 4]). It returns [4] when it should return [4, 4].

#12

@troy34: Is your return statement outside the for loop or inside?
Having such statement inside a loop instruction will simply interrupt the program execution and go back to where the function was called.

#13

yeah. I moved the return statement out of the loop a while ago and it worked… thanks