Lee Roy
Lee Roy

Reputation: 297

Compare two lists and remove first matching duplicate from list2

I have two lists and I'm trying to remove the first duplicate item from list2.

list1 =["cat"]
list2 = ["cat","dog","elephant","cat"]

expected output

list2 = ["dog","elephant","cat"]

I've tried using sets, but that removes ALL duplicates. I just want to remove the first duplicate found in the second list.

new_list = list(set(list2) - set(list1))

Upvotes: 0

Views: 587

Answers (1)

StardustGogeta
StardustGogeta

Reputation: 3406

Is this what you're looking for?

>>> list1 = ["cat"]
>>> list2 = ["cat", "dog", "elephant", "cat"]
>>> list2.remove(next(x for x in list1 if x in list2))
>>> list2
['dog', 'elephant', 'cat']

We use a list comprehension to find the common elements between the two lists, then just find and remove the first one.

Upvotes: 3

Related Questions