-1

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!

3 Answers3

2

Use the filter function to filter out any items present in both lists like this:

def array_diff(a, b):    
    return list(filter(lambda item: item not in ls2, ls1))

ls1 = [1, 2, 3, 4, 5]
ls2 = [2, 5]
print(array_diff(ls1, ls2))
AAAlex123
  • 347
  • 1
  • 8
0

there is a simpler approach eg.

a = [1,2,2,2,2,3]
b = [2]
c = list(set(a)-set(b)) # for output in list
print(c)
0

If you need only unique values then:

def array_diff(a, b):     
    return set(a) - set(b)
busfighter
  • 256
  • 1
  • 6