fbpx

Aliasing

Aliasing in Python refers to the situation where two or more variables refer to the same object or memory location. In other words, when two or more variables are assigned to the same object, any changes made to one variable will also affect the other variables.

				
					list1 = [1, 2, 3]
list2 = list1
list2.append(4)
 print(list1)
[1, 2, 3, 4]

				
			

In this example, we create a list called list1 with three elements. We then create a new variable called list2 and assign it to list1. This means that list2 is now an alias of list1. We then append the value 4 to list2. Since list2 is an alias of list1, this also modifies list1. As a result, when we print list1, it now contains four elements instead of three.

To avoid aliasing, you can create a copy of the object instead of assigning it to a new variable. For example, to create a copy of a list, you can use the copy() method or the slicing operator [:].

Loading...