0
Why does change1() affect the passed list but change2() does not?
And really, why does change1() change the list at all? I thought that the function has it's own namespace. So I dont see why id(list1) returns the same value in all three cases. I thought these would be different objects in all three cases. I've searched for how python handles namespaces and lists as arguements. Ive also read about variable scope and how variables can be global and how to establish them so. https://code.sololearn.com/cMVVEsp0s0NY/?ref=app
6 ответов
+ 1
It is a very weird behavior :
'+' operator calls the '__add__' magic method, which must return a new list (so à different list)
'+=' operator calls the '__iadd__' magic method, which modifies directly the object (for mutable objects at least : it would return a new string while working with strings). So no new list is created.
'append' method behaves in the same way of '+=' operator. However, when working with list, please prefer 'append' over '+=', in order to avoid this misunderstanding issues!
+ 1
In the second function:
def change2(list1):
print(id(list1))
list1 = list1 + [4]
This statement never happened:
list1 = list1 + [4]
If it did, id(list1) would have changed.
+ 1
Append doesn't change id, assignment does.
+ 1
Théophile Yep, I see now. Thank you! 🙂
0
Tomiwa Joseph Does python just not do the statement? If what you say is true, then it looks like the statement was just ignored.
https://code.sololearn.com/cIRVC4tAAWcc/?ref=app
0
Dan I explained what happens in my answer.