Your code does not work correctly because it does not keep track of how often an item from list2
has been used to discard a corresponding item from list1
.
Instead of building the differenceoflists
by adding items, you can create it by starting with a copy of list1
and removing all items from list2
. That way, corresponding pairs of items are matched exactly once, and if an item is contained more often in list1
than it is in list2
, the extras will remain.
To remove an item from a list you can use the remove
method. You need to handle the case when the item you try to remove isn't in the list (by just ignoring it).
def differenceoflists(list1, list2):
d = list1.copy()
for i in list2:
try:
d.remove(i)
except ValueError:
pass # ignore that i is not in list1
return d
There are some subtle differences in the order in which the items are contained in the result when comparing this code with the code shown in Jab's answer. Depending on your exact needs you need to choose one or the other.
differenceoflists
removes items from the left, while differenceoflists_jab
removes items from the right:
>>> differenceoflists([1, 3, 5, 1], [5, 1])
[3, 1]
>>> differenceoflists([1, 3, 5, 1], [1, 5])
[3, 1]
>>> differenceoflists_jab([1, 3, 5, 1], [5, 1])
[1, 3]
>>> differenceoflists_jab([1, 3, 5, 1], [1, 5])
[1, 3]
differenceoflists_jab
does not preserve the order of the items in list1
:
>>> differenceoflists([1, 3, 5, 1], [5])
[1, 3, 1]
>>> differenceoflists_jab([1, 3, 5, 1], [5])
[1, 1, 3]