I am trying to construct a Python function that finds the intersect between two lists. The output list should include all elements the two list share (including duplicates but won't exceed the amount the list with fewer of that element has). My first draft of the code looks like this:
def inter(list1, list2):
EmptySet = []
for i in list1:
if i in list2:
EmptySet.append(i)
list2.remove(i)
list1.remove(i)
return EmptySet
This code does not work with list1 = [1,2,2,1] and list2 = [2,2]. I try to put print statements within the code to check what list1 and list2 are after each operation, and apparently after encountering the first '2' in list 1, the function simply skips the second '2', leaving the end result to be list1 = [1,2,1] and list2 = [2]. I later on figured out the correct way (maybe not optimal) is to do this:
def inter(list1, list2):
EmptySet = []
for i in list1:
if i in list2:
EmptySet.append(i)
list2.remove(i)
return EmptySet
I realized why my first draft which deletes the element from list1 is unnecessary since the loop will simply pass to the next element and we only need to delete the matched element in list2 to prevent "overmatching" in list2, but I still can't figure out why my first draft of function behaves the way it does (skipping the second '2' or at least it seems to be).