In this article, we will see if if you change a list, say list y, it will also change list x. To do this, let's first look at an example with two lists and try to use append() and print for output -
x = [] y = x print("Value of y = ",y) print("Value of x = ",x) y.append(25) print("\nAfter changing...") print("Value of y = ",y) print("Value of x = ",x)
('Value of y = ', []) ('Value of x = ', []) After changing... ('Value of y = ', [25]) ('Value of x = ', [25])
Above, we saw that updating list y will also change list x.
We saw the above results because −
Above, writing y = x does not create a copy of the list. It creates a new variable y that refers to the same object as x refers to. This means there is only one object, the list, and both x and y refer to it.
When append() is called, the content of the variable object changes from [] to [25]. Since both variables point to the same object, the modified value can be accessed using either variable [25].
Suppose we assign an immutable object to x, then x and y will no longer be equal. This is because integers are immutable -
The Chinese translation of# ints are immutable x = 5 y = x print("Value of y = ",y) print("Value of x = ",x) # We are creating a new object x = x + 1 print("\nAfter changing...") print("Value of y = ",y) print("Value of x = ",x)
('Value of y = ', 5) ('Value of x = ', 5) After changing... ('Value of y = ', 5) ('Value of x = ', 6)
When we write x = x 1, we are not changing int 5 by increasing its value. Instead, we are creating a new object (int 6) and assigning it to x. After this assignment, we have two objects (int 6 and 5) and two variables referencing them.
therefore,
mutable object − If we have a mutable object, such as a list, dictionary, set, etc., we can use some specific operations to change it, and all variables that reference it will see to this change.
Immutable Object − If we have an immutable object like str, int, tuple, etc., all variables referencing it will always see the same value, but convert that value Operations on new values always return a new object.
The above is the detailed content of Why does changing list 'y' in Python also change list 'x'?. For more information, please follow other related articles on the PHP Chinese website!