Joseph A. Joseph A. - 22 days ago 4
Python Question

Find the element "left" in a list

I have the list

list1 = ["Hello", "Goodbye", "Ohai"]
.

I have another list,
list2 = ["Hello", "Goodbye"]
.

I want to get the remaining items in
list1
, in this case this would be
"Ohai"
.

Answer
>>> list1 = ["Hello", "Goodbye", "Ohai"]
>>> list2 = ["Hello", "Goodbye"]
>>> set(list1) ^ set(list2)
set(['Ohai'])

If you are supposed to use lists only, you can iterate:

>>> [item for item in list1 if item not in list2]
['Ohai']

But why do that when you have sets ;-)

Comments