You are confused between,
when we have different lists? and when an alias is created?.
As you have written:
list1=[1,2,3,4]
list2=list1
The above code snippet will map list1
to list2
.
To check whether two variables refer to the same object, you can use is
operator.
>>> list1 is list2
# will return "True"
In your example, Python created one list, reference by list1
& list2
. So there are two references to the same object. We can say that object [1,2,3,4]
is aliased as it has more than one name, and since lists are mutable. So changes made using list1
will affect list2
.
However, if you want to have different lists, you should do this:
>>> list1 = [1, 2, 3, 4]
>>> list2 = list1[:] # here list2 is created as a copy of list1
>>> list1.insert(4, 9)
>>> print list1
[1, 2, 3, 4, 9]
>>> print list2
[1, 2, 3, 4]