Reputation: 1494
So, here is a piece of code:
def function(item, stuff = []):
stuff.append(item)
print stuff
function(1)
# print '[1]'
function(2)
# print '[1,2]'
As I understood, this shows, that default values, changed during program run still changed at every function calls. But why this piece of code:
def function(item, stuff = 0):
stuff += item
print stuff
function(3)
function(3)
prints '3' at every runs?
Upvotes: 0
Views: 42
Reputation: 23264
Lists in Python are mutable: They can be modified after they have been created. That's why the stuff
list grows when you call the first function, it's the same list object each time.
Integers on the other hand are immutable. You cannot change them after you have them created. So what this does
a = 2
a += 1
is to remove the a
label from the "2" object and attach it to the "3" object instead.
That's why the "0" object (the default value for the stuff
argument of the second function) remains unchanged and you get 3 everytime.
Upvotes: 2