They do not behave differently. Changes to x
are never reflected in y
.
x = [1,3,6,[18]]
y = list(x)
print(y) # [1,3,6,[18]]
x[3] = [15]
print(y) # [1,3,6,[18]]
However, changes to the 1-element list are reflected both in x
and in y
:
z = [18]
x = [1,3,6,z]
y = list(x)
print(y) # [1,3,6,[18]]
z[0] = 15
print(y) # [1,3,6,[15]]
The reason why integers and lists are different, the reason why you don't see changes to integers reflected in y
is because it's possible to make changes to a list, but it's not possible to make changes to int
:
x = [1,3,6,[18]]
y = list(x)
print(y) # [1,3,6,[18]]
3 = 12 # SyntaxError: cannot assign to literal here.
In python, every type is either mutable or immutable. Lists are mutable; integers are immutable.