1

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!

Jinzo
  • 23
  • 3
  • 4
    `b = c1` doesn't make a new list. – user2357112 May 16 '20 at 02:39
  • 1
    use list.copy() instead. – sage07 May 16 '20 at 02:52
  • "This is a code fragment I extracted from my bigger program and it is enough to replicate the problem I encountered." thank you for that! – juanpa.arrivillaga May 16 '20 at 03:25
  • 1
    Hi, note that list are mutable whereas other data types such as strings are immutable. By referencing b = c1 and then modify c1, you are also mutating b (because of the mutable property of the list data type). The way around this is to use: b = c1.copy(). – anveshjhuboo May 16 '20 at 04:27
  • Thanks for the answers. I never thought the problem was there. I find it very weird the way it works, but I guess a have to go back a bit and look at the basics some more. – Jinzo May 17 '20 at 04:45

0 Answers0