I'm trying to write a function that takes as input two lists: def array_diff(a, b):
. In this function, I would like to return a filtered a
list that will have been removed all items that are also present in list b
. It will work as such:
array_diff([1,2],[1]) == [2]
Or:
array_diff([1,2,2,2,3],[2]) == [1,3]
I have written the following code:
def array_diff(a, b):
for i in a:
if i in b:
a.remove(i)
return a
But even though I get no errors, when I try to run this function and list a
has two items with the same value, and it is present in list b
, it doesn't filter it properly. I'm not sure why this is happening, but I already tried using a.pop(i)
as well, but also didn't work. I also tried iterating over the list with for i in range(len(a))
, but I get errors saying I went over the list's index.
Hopefully, you can help me, thank you!