Subtracting one list from another in Python

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

What's currently going on: My first function only works if there is only one number left in list a.

What I've tried: Turning lists into groups and then subtracting a - b

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

      

Also tried: Switching the list to groups, searching for n in and m in b and then 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

      

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

I / O example:

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

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

+3


source to share


1 answer


Just use it like this:



 c = [x for x in a if x not in b]

      

+3


source







All Articles