21

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
    Can't you just loop over 1 list and remove from the other? – Carcigenicate May 14 '17 at 20:13
  • Look at the duplicate. Ultimately you just alter the condition you want for your list comparison. But there are several examples of what you are trying to do throughout StackOverflow. – idjaw May 14 '17 at 20:17

1 Answers1

53

Just use it like that :

 c = [x for x in a if x not in b]
Daniel Taub
  • 5,133
  • 7
  • 42
  • 72