+ 1

Python lists

I’m just a beginner so this is probably really basic, but why does this a = [1, 2, 3, 4] b= a b = b.remove(4) print(a) Output [1, 2, 3] Shouldn’t a and b be independent from each other?

19th Feb 2022, 5:46 AM
Interesting
Interesting - avatar
5 Answers
+ 6
It is because 'b' is not a copy of 'a'. Reference of 'a' is assigned to 'b'. It means both the variables are pointing to the same list in the memory. You can use either one of them to make any changes to the list and it will be reflected in both.
19th Feb 2022, 6:04 AM
Avinesh
Avinesh - avatar
+ 3
Hi, ES135! You can look at this one: https://code.sololearn.com/c6HP42TW4Q5O/?ref=app If you don’t want a and b to be referenced to the same object, you can do a (shallow) copy of the list: b = a[:] or b = a.copy().
19th Feb 2022, 6:50 AM
Per Bratthammar
Per Bratthammar - avatar
+ 2
Thank you for all the answers :)
20th Feb 2022, 1:05 PM
Interesting
Interesting - avatar
+ 1
a is assigned to b. So when you print 'b' it should output 1, 2, 3, 4. So when you remove 4 from b you are removing 4 from the list. Therefore it outputs 1, 2, 3
20th Feb 2022, 11:32 AM
Bubble Tea
Bubble Tea - avatar