5
def a(b=[]):
    b.append(1)
    return b

print a()
print a()

All of a sudden i got a list with 2 elems, but how? Shouldn't b be getting set to empty list every time.

Thanks for the help

1

4 Answers 4

10

Default arguments are only evaluated once, when the function is defined. It retains the same object from one invocation to the next, which means that the same list keeps getting appended to. Use a default value of None and check for that instead if you want to get around this.

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

Comments

9

Nothing to do with closures, at least not in the usual sense.

The default value for b is not "a new empty list"; it is "this particular object which I just created right now while defining the function, initializing it to be an empty list". Every time the function is called without an argument, the same object is used.

Comments

3

The corrected version, for the reasons given in other answers, is:

def a(b=None):
    b = [] if b is None else b

    b.append(1)
    return b

Comments

1

default arguments are evaluated (once) when the function is defined, not each time it is called.

try this:

def a(b=None):
    if b is None
        b = []     
    b.append(1)
    return b

print a()
print a()

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.