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.

8th Jan 2020, 12:25 PM
hanumant rajain
hanumant rajain - avatar
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.
8th Jan 2020, 12:33 PM
Pie
Pie - avatar
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 馃槀馃槀
8th Jan 2020, 12:33 PM
Pattern
Pattern - avatar
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!!!
8th Jan 2020, 12:47 PM
hanumant rajain
hanumant rajain - avatar
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.
8th Jan 2020, 1:21 PM
HonFu
HonFu - avatar