This question already has an answer here:
- How do I pass a variable by reference? 23 answers
In the python code below, variable number
is passed to the function addone
, and a local copy is operated on. The value of number stays the same.
def addone(num):
num = num + 1
print "function: added 1, now %d" % num
number = 5
print "Before:", number
addone(number)
print "After:", number
Output :
Before: 5
function: added 1, now 6
After: 5
However, the behavior appears to be different with list operations like pop, append etc. This somewhat confuses me. Do all list operations operate globally ? If so, is there any particular reason behind it ?
def pop_first(stuff):
popped = stuff.pop(0)
print "function: '%s' was popped!" % popped
words = ["A", "list", "of", "words"]
print "Before:", words
pop_first(words)
print "After:", words
Output :
Before: ['A', 'list', 'of', 'words']
function: 'A' was popped!
After: ['list', 'of', 'words']
The short answer is because lists are mutable and integers are immutable.
You cannot mutate an integer in place, so we call it 'immutable'. With this in mind, things like addition on an integer do not modify the original object, but rather return a new value- so your original variable will remain the same. Therefore, if we store a reference to an integer, they will only be the same object as long as we have not changed either one of them:
On the other hand lists are 'mutable' (can modify that same object reference), and operations like
pop()
mutate thelist
in-place, changing the original. This also means that if you edit a reference to a mutable object such as alist
, the original will be changed as well:Passing objects to functions works the same way as assigning them. So, what you're seeing is the same effect as this:
This happens because
stuff
andwords
are the same list, andpop
changes that list. ints are immutable, meaning they don't support any in-place mutations: every time you change its value, it gives you a different int object with the new value. You can test whether two objects are the same or distinct objects using theis
operator:When you do
stuff.pop()
you modify the objectstuff
. When you donum = num + 1
you don't modifynum
, you just create a new object and assign it to the variablenum
. Ifnum
were a list, the result would be exactly the same: