-3
def purify(ls):
    y = ls
    for i in ls:
        if i % 2 != 0:
          y = y.remove(i)

    print y

The following code fails when I pass the list (4, 5, 5, 4). It returns (4, 5, 4) instead of (4, 4). What is wrong here ? I am not able to understand why changes in y list is affecting original list ls.

Mohan.W
  • 1
  • 2

4 Answers4

1

Do like this.

In [1]: a = (4, 5, 5, 4)
In [2]: result = [i for i in a if not i % 2]
In [3]: result
Out[1]: [4, 4]

In function.

def purify(ls):
   return [i for i in ls if not i % 2]

To understand more i expand my code.From this you can understand how it's work.

def purify(input_list):
    result = []
    for i in input_list:
        if not i % 2:
            result.append(i)
    return result
Rahul K P
  • 15,740
  • 4
  • 35
  • 52
1

The indices change once you start removing items. It is not a good practice to iterate on a list while you're mutating its items in the loop. Iterate on a slice of the list ls[:] instead:

def purify(ls):
    for i in ls[:]:
        if i % 2 != 0:
            ls.remove(i)

Or just use a list comprehension:

[i for i in ls if i % 2 == 0]
Moses Koledoye
  • 77,341
  • 8
  • 133
  • 139
  • But I am editing the list y and not original list ls. I am not able to understand why remove function on y list is affecting original list ls. – Mohan.W Jun 16 '16 at 21:03
  • The two variables are pointing to the same object. So if you do `x = y = ['a']` and then `x[0] = 4`, `y` gets updated also. – Moses Koledoye Jun 16 '16 at 21:05
0

The following code is much cleaner and easier to understand:

l = [4, 5, 5, 4]

l = filter(lambda x: x % 2 == 0, l)

print(l)

[4, 4]

Simon Kirsten
  • 2,542
  • 18
  • 21
0
remove(...)
    L.remove(value) -- remove first occurrence of value.
    Raises ValueError if the value is not present.

correct version:

>>> filter(lambda x: x % 2 == 0, [4, 5, 5, 4])
[4, 4]

your correct version:

def purify(ls):
    y = ls[:]  # copy it instead of refering to it
    for i in ls:
        if i % 2 != 0:
            y.remove(i)  # remove will return none

    print y
ZhiQiang Fan
  • 986
  • 6
  • 7