[ACCEPTED]-Python Variable Scope (passing by reference or copy?)-scope
Long story short: Python uses pass-by-value, but 19 the things that are passed by value are 18 references. The actual objects have 0 to 17 infinity references pointing at them, and 16 for purposes of mutating that object, it 15 doesn't matter who you are and how you got 14 a reference to the object.
Going through 13 your example step by step:
L = [...]creates a
listobject somewhere in memory, the local variable
Lstores a reference to that object.
sorting(strictly speaking, the callable object pointed to be the global name
sorting) gets called with a copy of the reference stored by
L, and stores it in a local called
- The method
sortof the object pointed to by the reference contained in
xis invoked. It gets a reference to the object (in the
selfparameter) as well. It somehow mutates that object (the object, not some reference to the object, which is merely more than a memory address).
- Now, since references were copied, but not the object the references point to, all the other references we discussed still point to the same object. The one object that was modified "in-place".
testScopethen returns another reference to that list object.
__str__method) and outputs it. Since it's still the same object, of course it's printing the sorted list.
So whenever you 12 pass an object anywhere, you share it with whoever 11 recives it. Functions can (but usually won't) mutate 10 the objects (pointed to by the references) they 9 are passed, from calling mutating methods 8 to assigning members. Note though that assigning 7 a member is different from assigning a plain 6 ol' name - which merely means mutating your 5 local scope, not any of the caller's objects. So 4 you can't mutate the caller's locals (this 3 is why it's not pass-by-reference).
Further 2 reading: A discussion on effbot.org why it's not pass-by-reference 1 and not what most people would call pass-by-value.
Python has the concept of Mutable and Immutable objects. An 7 object like a string or integer is immutable 6 - every change you make creates a new string 5 or integer.
Lists are mutable and can be 4 manipulated in place. See below.
a = [1, 2, 3] b = [1, 2, 3] c = a print a is b, a is c # False True print a, b, c # [1, 2, 3] [1, 2, 3] [1, 2, 3] a.reverse() print a, b, c # [3, 2, 1] [1, 2, 3] [3, 2, 1] print a is b, a is c # False True
Note how 3 c was reversed, because c "is" a. There 2 are many ways to copy a list to a new object 1 in memory. An easy method is to slice:
c = a[:]
It's specifically mentioned in the documentation 4 the
.sort() function mutates the collection. If 3 you want to iterate over a sorted collection 2 use
sorted(L) instead. This provides a generator 1 instead of just sorting the list.
a = 1 b = a a = 2 print b
References are not the same as separate 1 objects.
.sort() also mutates the collection.
More Related questions