-1

In python, remove() is supposed to remove the first occurence of a value in the list. I tried the code below, however it doesn't remove all values found in list b from list a. Is there anything wrong with my code?

def array_diff(a,b):
    for i in a:
        if i in b:
            a.remove(i)
    return a

for example, it prints out [1, 2, 3] when it only should print [1, 3]

print(array_diff([1,2,2,2,3],[2]))
> [1, 2, 3]

additional note: I'm aware of a shorter version (shown below) that works as it should but I would like to know what's wrong with my code above? Thank you!!!

def array_diff(a, b):
    a = list(i for i in a if i not in b)
    return a
airbee
  • 1
  • Since you are modifying the list while iterating, the second `2` in the list is skipped. – ywbaek Jul 23 '20 at 13:52
  • By the by, `list(i for i in a if i not in b)` should really just be `[i for i in a if i not in b]`; the former makes a generator expression, then consumes it item by item to build the `list`, which means you have generator overhead you don't actually need, the latter builds the new `list` directly via a true list comprehension. – ShadowRanger Jul 23 '20 at 13:52
  • `list(set(list1) - set(list2))` does what you want in single line. – Ach113 Jul 23 '20 at 13:54

1 Answers1

0

I decided not delete just return new list for you:

def array_diff(a,b):
    new = []
    for i in a:
        if i not in b:
            new.append(i)
    return new


print(array_diff([1,2,2,2,3],[2]))


def array_diff2(a,b):
    return [i for i in a if i not in b]


print(array_diff([1,2,2,2,3],[2]))