+ 1

List

a=[3,5,7,9] b=a a[1]=8 print(b[1]) Output: 8 Why when we changes the value in a-list it changes in b list also and vice versa?

15th Jan 2020, 6:23 PM
Š‘Š¾Š³Š“Š°Š½ Š‘Š¾Š³Š“Š°Š½Š¾Š²Šøч
Š‘Š¾Š³Š“Š°Š½ Š‘Š¾Š³Š“Š°Š½Š¾Š²Šøч - avatar
3 Answers
+ 7
What you did in your code is a so called shallow copy. Both lists a and b have the same object id, so they are referencing the same object. To get 2 independent objects you can use copy() when you create b in this case. b=a.copy() An other way to make an independent copy is to use a slice: b = a[:] If your source list is a compound list (means that it contains e.g. lists), you have to use deep copy. So the code has to be: from copy import deepcopy a = [1,2,3,[11,9]] b = deepcopy(a) In this case b will be independent from a, and also [11,9] will be independent from sub list in a.
15th Jan 2020, 6:31 PM
Lothar
Lothar - avatar
+ 3
Lothar is right Because a and b have the same object id , so if you change the value of a ,it is going to change the value of b ,because it is a shallow copy. So,there are many ways to create an independent copy like this a = [1,2,3] b = list(a) # this is going to create an independent copy or by using copy() method like this a = [1,2,3] b = a.copy() You can check that by using id() Id shows us that a and b have different addresses id gives us the address of the object and everything is just an object in python and lists are also objects. And if you have a compound list that is lists of lists or in other words a list that contains lists Then we can also use list comprehensions for deep copies like this a =[[1,2],[3,4] b = [[x for x in lis] for lis in a] And if you have any doubt about all this , feel free to message me šŸ˜ƒ
15th Jan 2020, 6:58 PM
Elliot
Elliot - avatar
+ 1
@Lothar, Thanks a lot!
15th Jan 2020, 6:41 PM
Š‘Š¾Š³Š“Š°Š½ Š‘Š¾Š³Š“Š°Š½Š¾Š²Šøч
Š‘Š¾Š³Š“Š°Š½ Š‘Š¾Š³Š“Š°Š½Š¾Š²Šøч - avatar