Search code examples
pythonarraysslicemutability

Difference between full variable shallow copying and slice partial copying


From what I understand, Python is a pass by object reference language, which means that if the original value is mutable, every shallow copy will be affected (and vice versa). So, something like:

x = [1,2,3]
y = x
x.append(4)
print(y[-1]) -> 4

Is an expected consequence of the mutability of arrays. But when I make a shallow copy using the slicing operator:

x = [1,2,3]
y = x[:]
x.append(4)
print(y[-1]) -> 3

Why is this behavior happening?


Solution

  • id built-in function will help. As will the is operator.

    x = [1,2,3]
    y = x
    print(y == x) # True
    print(y is x) # True
    print(id(y) == id(x)) # True
    

    So all are true. x and y have the same values, they occupy the same space in memory.

    x = [1,2,3]
    y = x[:]
    print(y == x) # True
    print(y is x) # False
    print(id(y) == id(x)) # False
    

    Only == operator is true. x and y share the same values. However, they exist in two different memory locations.