0

I am new to Python and to coding, and I am running in to a challenge. I am trying to remove all values from "list_a" that are present in "list_b." The inputs passed through the function must be lists, they can't be any other data type.

For example, [1,2,2,2,3], [2] should return [1, 3].

My attempt is below, but it returns [1, 2, 3] which is wrong. I'm stuck and would appreciate some help on how to do this the right way, please.

def changeup(list_a, list_b):
    for i in list_b:
        for k in list_a:
            if k == i:
                list_a.remove(k)

    return list_a

changeup([1,2,2,2,3],[2])

#This is returning [1, 2, 3].  It should be returning [1, 3].  Not sure why?
  • 3
    Mutating list while iterating through is not the correct way to do it. It produces undesired results. Instead work on copy of the list you want to modify. – Ch3steR Mar 12 '20 at 19:11
  • Additionally, in the interest of better readability, that you would reserve i for going over a list by its index. `for item_a in list a` would be better, in my opinion. – user2182857 Mar 12 '20 at 19:18
  • You are iterating on list_a and that the same time removing items in it. You may copy this to a temp list and operate on that copy def changeup(list_a, list_b): from copy import copy list_a_cp = copy(list_a) for i in list_b: for k in list_a: if k == i: list_a_cp.remove(k) return list_a_cp changeup([1,2,2,2,3],[2]) Out:[1, 3] – jose_bacoy Mar 12 '20 at 19:47

1 Answers1

1

Try this:

list_a = list(set([item for item in list_a if item not in list_b]))

If you want want to keep duplicated values.

list_a = [item for item in list_a if item not in list_b]

Iterate through one list to see if the item is in the other

Peter
  • 169
  • 5
  • 1
    This is a `O(m * n)` solution; proper use of `set` could get it down to `O(m + n)` (and still avoid discarding duplicates) so long as the values are hashable. `set_b = frozenset(list_b)` then `list_a = [item for item in list_a if item not in set_b]`. – ShadowRanger Mar 12 '20 at 19:17