Purify HELP


Oops, try again. Your function fails on purify([4, 5, 5, 4]). It returns [4, 5, 4] when it should return [4, 4].

def purify(lista):
    for item in lista:
        if item % 2 != 0:
    return lista


Removing an element causes all the following elements to move one step to 1 index lower, something that you aren't accounting for, not to mention that all this moving probably isn't something you want to happen anyway, so remove is not what you want at all. Reconsider what action you want, how would you do it manually? Your program should do the same thing, you should implement that


thank you i solved it !

def purify(lista):
    for item in lista:
        if item % 2 != 0:
    return lista


That is an incredibly nasty work-around though. You get a huge amount of operations that will have no effect, you would never do it that way manually.


why!! never heard of recursion ?


Technically that is recursion, but you aren't leveraging recursion, you're just using it to re-start the loop, but you're still finishing the loop afterwards


What you'd want to do is create a new list with all even numbers included.

Alternatively, you could have two indexes, one where you write and one where you read, you would increase the read index by one until you've read them all, and you would write at the write-index each time an even number is found. By the end you would then resize the list.. However, this is going to be as many operations as just creating a new list, and it's more complicated.

In a functional language you would look at the head (first element) and return the head followed by purify(rest) if the head is even, otherwise you would only return purify(rest) where "rest" is everything but the first element. This doesn't fit very well into Python though.


i come from c# ...but thank you for the answer


The same would apply to C#


I don't really do C#, but I gave a shot at translating:

using System.Collections.Generic;

public class Purify
    public static void Main()
        // create some list to use as input
        List<int> myList = new List<int> {1, 2, 3, 4, 5, 6};

        // print out each value that's left after purifying
        foreach (int v in purify(myList)) {

    public static List<int> purify(List<int> list)
        foreach (int value in list) {
            if (value % 2 == 1) {
        return list;

What happens on running that is that there's a runtime error:

Unhandled Exception:
System.InvalidOperationException: Collection was modified; enumeration operation may not execute.

So.. the language just doesn't allow something that's error prone


(post withdrawn by author, will be automatically deleted in 24 hours unless flagged)


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