0
List assignment
in the below code: a=[1,2,3,4] b=a a.append(5) a=b when we append something in list a, why it gets added in list b.
4 Answers
0
I believe because when lists are created and you set another value equal to it you are no saving a copy you are saving the pointer to that previous list.
If you want to not have this happen do a.copy() or b.copy() to create a seperate list.
In your example:
a=[1,2,3,4]
b=a.copy()
a.append(5)
a=b
a would be the same as the original by the end of this.
0
You are saying that a is b its like the US is the same as America so if you build a new thing in America it will be built in the US as well đđ
0
it seems when we assign b=a, it creates link between them. any change in a will be reflected in b also. a.copy() works!!!
0
In Python, when you assign, it's like putting a sticker onto an object.
a = []
Here a new list is created (because you wrote that literal), and then the name a is given to that list.
Now b=a puts another sticker on that object that already exists.
We now have one list with two names: a and b.