Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Why did changing list 'y' also change list 'x' in Python?
In Python, when you assign one list variable to another using y = x, both variables point to the same object in memory. This means modifying one list will affect the other, which often surprises beginners.
Example: Lists Share the Same Reference
Let's see what happens when we assign one list to another and then modify it ?
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 also changed list x.
Why This Happens
This behavior occurs because ?
- Lists are mutable objects ? you can change their content after creation
- Variables are names that refer to objects in memory
- The assignment
y = xdoesn't create a copy ? it makesypoint to the same object asx
When append() is called on y, it modifies the shared list object. Since both variables refer to the same object, both show the modified value [25].
Example: Immutable Objects Behave Differently
With immutable objects like integers, this sharing doesn't cause the same issue ?
# 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're not changing the integer 5. Instead, we create a new integer object (6) and assign it to x. Now x and y refer to different objects.
Solutions: Creating Independent Copies
To avoid shared references with lists, create a copy instead ?
x = [1, 2, 3]
y = x.copy() # or y = x[:]
x.append(4)
print("x =", x)
print("y =", y)
x = [1, 2, 3, 4] y = [1, 2, 3]
Key Points
- Mutable Objects ? Lists, dictionaries, sets can be modified in-place. All variables referencing them see the changes.
- Immutable Objects ? Strings, integers, tuples cannot be changed. Operations create new objects instead.
-
Assignment ?
y = xcreates a reference, not a copy. Usecopy()or slicing for independent lists.
Conclusion
Understanding Python's reference system prevents unexpected behavior when working with mutable objects. Use copy() methods when you need independent list copies rather than shared references.
