12/15 purify


#1

I'm not sure why this function doesn't work...the error I get is "Your function fails on purify([4, 5, 5, 4]). It returns [4, 5, 4] when it should return [4, 4]." However, I thought that a for loop would iterate through the entire list? Why is one of the 5s purified and the other not? Thanks.

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

#2

removing elemaents from a list while iterating it is a bad ideas because it tends to mess up the iterator. Best bet is to use a new list and only add the elements you want


#3

Remember to read and reread the instructions.
Here we are asked to not modify the List but to
create a new list from the original. (As we may wish
to preserve the original list for some other task)

Anyway here is my Solution, though I would say
fiddle around and try and come up with an even
better more efficient way of achieving this.

def purify(numbers):
        x = []
        for i in numbers:
            if i % 2 == 0:
                x.append(i)
            else:
                continue
        return(x)

#4

I think this is a pretty concise solution:

def purify(lst):
    res = []
    for j in lst:
        if j % 2 == 0: res.append(j)
    return res

#5

Or using list comprehension:

def purify(lst):
    return [j for j in lst if j % 2 == 0]

Python can be pretty sweet. It does become a bit of a trade off between size and readability though.


#6

This is in my opinion the best way to do it. List comprehension is a fast and effective, easy way!


#7

I did something similar to bytesurfer except that I started by making a copy of list and removing items from the copy.

def purify(list):
copy = list
for x in list:
if x % 2 == 1:
copy.remove(x)
return copy

My goal was not to change the original list, but to remove from the copy. For some reason my original list is changing and I don't know why. Can someone tell my why my code above would change the original list?


#8

@terapro13133: I think you could've created a new topic for your question other than posting here but anyway, the problem is that you didn't really make a "copy" of the list, you just passed the reference of it, just like you did when you called the function purify() passing the name of the list to it.
In that case, you'll be able to manipulate that list using either copy or list.

In order to really copy it, you could've done the following:
1) newList = oldList[:]
2) newList = list(oldList)

Both ways would keep your original list and only change the copy of it.

Best regards,
G4be