I'm trying to add new unique values to a list in Python then check to see if any new values were actually added to the list. This is a code fragment I extracted from my bigger program and it is enough to replicate the problem I encountered.
from collections import Counter
def expand_list(existing_list, new_list):
for elem in new_list:
if elem not in existing_list:
existing_list.append(elem)
return existing_list
c1 = [1, 2]
c2 = [3, 4, 5]
b = c1
expand_list(c1, c2)
print(c1)
print(b)
print(Counter(b) != Counter(c1))
When I execute this is the result
[1, 2, 3, 4, 5]
[1, 2, 3, 4, 5]
False
For reason I cannot understand c1 is changed before it is copied into b, even though the function is called after I create b with the values from c1.
This is what I expected when I ran this code
[1, 2, 3, 4, 5]
[1, 2]
True
Can someone please explain to me why this is happening and how I can successfully save c1 into b before it is modified by the function?
Thank you!