0

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?

1
  • Looks like stuffis re-initialized on every call. Commented Mar 2, 2015 at 15:26

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.