12/15 purify- why this code don't work?


#1

I tried it this way-
def purify(n):
for i in n:
if i%2 == 1:
n.remove(i)
return n

But it didn't work. Not only for that the requirement was to create a new list, not modifying the older one, but also it failed in test. My question is, why?


#2

It doesn't work because you remove numbers from n, while you are in the loop. So this is what happens;

example [4,5,5,4]
1st loop - n[0] = 4 - nothing happens
2nd loop - n[1] = 5 - first 5 gets removed from n. n is now [4,5,4]
3rd loop - n[2] = 4 - !!!

So what can you do; either make a new list and use append to build it up with the correct numbers. Or make a copy of n using the following method:

import copy
o = copy.copy(n)

and then use n for the loop, but remove the numbers from o instead.


#3

Something I found confusing here is why it wouldn't work for me to just make a copy of n using new_n = n.

In addition to using the copy module or appending items to the new list, you can use new_n = list(n)


#4

It's the way these lists are saved in Python. By saying new_n = n you don't copy the list; you only add a reference to the same list. Thus any change made changes 'both'. Example;

a = [1,2,3,4]
b = a
a = a.append(5)
print b

Will result into [1,2,3,4,5]


#5

I have the same problem here but after trying changing codes many times
I got out with this code very simple and can be understood easily:
def purify(numbers):
result = []
for x in numbers:
if x % 2 == 0:
result.append(x)
return result
return True
print purify([4,5,5,4])


#6

This works for me :smile:
def purify(i):
copy = []
for a in i:
if a % 2 != 0:
copy.append(a)
for b in copy:
i.remove(b)
return i