Skip to content Skip to sidebar Skip to footer

How To Remove The Items In A List That Are In A Second List In Python?

I have a list of lists, and another list, and I want to remove all of the items from the list of lists that are in the second list. first = [[1,3,2,4],[1,2],[3,4,2,5,1]] to_remove

Solution 1:


result = []
for l in first:
    tmp = []
    for e in l:
        if e not in to_remove:
            tmp.append(e)
    result.append(tmp)

print(result)

This code loop over all the list and all the element of each list if the element is in to_remove list it skip it and go to the next. so if you have multiple intance it will remove it

Best regard

Solution 2:

An elegant solution using sets:

first = [[1,3,2,4],[1,2],[3,4,2,5,1]]
to_remove = [1,2]
result = [list(set(x).difference(to_remove)) for x in first]
result
[[3, 4], [], [3, 4, 5]]

Post a Comment for "How To Remove The Items In A List That Are In A Second List In Python?"