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']