Skip to content Skip to sidebar Skip to footer

Python Variable Scope (passing By Reference Or Copy?)

Why does the variable L gets manipulated in the sorting(L) function call? In other languages, a copy of L would be passed through to sorting() as a copy so that any changes to x w

Solution 1:

Python has the concept of Mutable and Immutable objects. An object like a string or integer is immutable - every change you make creates a new string or integer.

Lists are mutable and can be manipulated in place. See below.

a = [1, 2, 3]
b = [1, 2, 3]
c = a

print a is b, a is c
# False Trueprint 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 c was reversed, because c "is" a. There are many ways to copy a list to a new object in memory. An easy method is to slice: c = a[:]

Solution 2:

It's specifically mentioned in the documentation the .sort() function mutates the collection. If you want to iterate over a sorted collection use sorted(L) instead. This provides a generator instead of just sorting the list.

Solution 3:

a = 1
b = a
a = 2
print b

References are not the same as separate objects.

.sort() also mutates the collection.

Post a Comment for "Python Variable Scope (passing By Reference Or Copy?)"