+ 7

Why list2 and list4 are different ?

https://code.sololearn.com/cT51IGQL2fgH/?ref=app list = list + [5] and list += [5] is not same? Why???

4th May 2019, 7:29 PM
UraL
6 Respostas
+ 3
In your line list1 = list1+[5], you are creating a new list. Basically you strip off the name sticker from list1 and paste it to a new list object. If you had used += instead, you would have changed the list 'in-place' and it would still be the same object.
4th May 2019, 7:33 PM
HonFu
HonFu - avatar
+ 9
HonFu, thanx. Very interesting, Python so mysterious sometimes.
5th May 2019, 9:02 AM
UraL
+ 8
Bravo !!!
5th May 2019, 5:46 PM
UraL
+ 2
That's quite interesting behavour. Wouldn't have expected that. Quite the possible trap for errors that are hard to spot if you are not aware of that. Python must be treating strings as reference types but changing that if you assign a new value not using the += operation and thus working with the same object? JS, für example, does not behave that way. In both cases the value is transfered because it is a string and thus treated as an value object. I have also tested an array since that's a reference object and there the reference is stored, meaning: add 5 to one and the other will show the same result since it's the same object. I would expect the same in C# but have not tested it. Edit: Just tested resetting the first array to [ ] and it behaved the same way by losing it's reference to its object and creating a new one apparently. https://code.sololearn.com/W0ES4QPr6o5h/?ref=app
5th May 2019, 9:22 AM
Michael U.
Michael U. - avatar
+ 2
In Python, everything is a reference; if an object can be changed or not, is controlled by the types themselves (duck typing!). There are immutable types, that whenever you use one of their methods to 'change' them, secretly make a copy, a new object, instead. Then there are mutable objects that have ways to change them in-place, like you can append new elements to lists. Assignment is always name-stripping. So the name is given to a new object - which doesn't necessarily mean that the old object is erased - it may have other names. += is an operator overload. For lists it is defined to change the actual object (duck typing again). Yeah, it can be confusing at times, but I suppose you have to know all of these little tricks in every language, like in JS, where numbers can turn into strings like by magic if you use +, and strings as numbers if you use *. Anyway, lists and their reference behavior tend to trip you up in Python, so no surprise there are a lot of challenge quizzes about that.
5th May 2019, 10:17 AM
HonFu
HonFu - avatar
+ 2
HonFu A very well formulated and insightful answer. Thank you. :)
5th May 2019, 10:30 AM
Michael U.
Michael U. - avatar