Subtracting one list from another in Python

Viewed 38280

What I want to happen: When given two lists (list a and list b), remove the numbers in list a that are in list b.

What currently happens: My first function works only if list a has only one number to be removed.

What I've tried: Turning the lists into sets, then subtracting a - b

def array_diff(a, b):
  c = list(set(a) - set(b))
  return c

Also tried: Turning the list into sets, looking for n in a and m in b, then if n = m to remove n.

def array_diff(a, b):
  list(set(a))
  list(set(b))
  for n in (a): 
    for m in (b):
      if n == m:
        n.remove()

        return a

Possibly thought about: Using the "not in" function to determine if something is in b or not.

Sample Input/Output:

INPUT: array_diff([1,2], [1]) OUTPUT: [2]

INPUT: array_diff([1,2,2], [1]) OUTPUT: [2] (This should come out to be [2,2]

1 Answers
Related