Assignment by reference

When we assign a variable to another variable, it is done by reference. This means that both variables will refer to the same object in memory. Let's look at an example:

list1 = [1, 2, 3]
list2 = list1

In this example, we have two variables: list1 and list2. We assign list1 to list2 using the equals sign. Now, both list1 and list2 refer to the same list object [1, 2, 3].

What this means is that if we make changes to the list through one variable, it will affect the other variable as well. For example:


In this code, we use the append() method to add the value 4 to list1. If we print list2 after this, we will see that it also contains [1, 2, 3, 4]. This is because list2 is just another name for the same list object.

The same concept applies to other mutable objects in Python, such as dictionaries or sets. When you assign a mutable object to another variable, both variables will refer to the same object.

On the other hand, if you assign an immutable object (like a number or a string) to another variable, a new copy of the object is created. Here is an example:

x = 5
y = x
x = 10

In this code, we assign the value 5 to x, and then assign x to y. After that, we update x to have the value 10. If we print y after this, it will still be 5. This is because y is a separate copy of the original value, not a reference to x.