Why did changing list ‘y’ also change list ‘x’ in Python?


Example

In this article, we will see if you will change a list, let’s say List y will also change list x. For this, let us first see an example with two lists and try to append() and print −

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)

Output

('Value of y = ', [])
('Value of x = ', [])

After changing...
('Value of y = ', [25])
('Value of x = ', [25])

Above, we saw that updating list y change list x as well.

We saw the above result because −

  • Lists are mutable i.e. you can change their content.
  • Variables are names that refer to objects.

Above, writing y = x doesn’t create a copy of the list. It create a new variable y that refers to the same object x refers to. This means that there is only one object i.e. the List, and both x and y refer to it.

When the append() is called, the content of the mutable object changed from [] to [25]. Since both the variables refer to the same object, using either name accesses the modified value [25].

Let’s say if we instead assign an immutable object to x, the x and y are not equal anymore. This is because integers are immutable −

Example

# 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)

Output

('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 mutating the int 5 by incrementing its value. Instead, we are creating a new object (int 6) and assigning it to x. After this assignment we have two objects (ints 6 & 5) and two variables referring them.

Therefore,

  • Mutable Object − If we have a mutable object, such as list, dict, set, etc., we can use some specific operations to mutate it and all the variables that refer to it will see the change.

  • Immutable Object − If we have an immutable object, such as str, int, tuple, etc., all the variables referring to it will always see the same value, but operations that transform that value into a new value always return a new object.

Updated on: 19-Sep-2022

122 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements