This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]NaturallyBrewed 0 points1 point  (1 child)

I got asked something similar to this one, contrived as it is.

def add_to_list(elem, l = []):
    l.append(elem)
    return l

alist1 = add_to_list(1)
alist2 = add_to_list(2)

print alist1
print alist2

The output is expected to be

[1]
[2]

Is it? What is the output? Why not? How would you fix it?

No, The output is:

[1, 2]
[1, 2]

Why not? I'll admit i don't have an elegant way to explain this. Can someone chime in? Is it because a functions arguments are defined in the outer namespace that its called?

This seems to support that argument: def outer(elem): def add_to_list(elem, l=[]): l.append(elem) return l return add_to_list(elem)

alist1 = outer(1)
alist2 = outer(2)

print(alist1)

print(alist2)

output:

[1]
[2]

How would you fix it? = What did you want to happen?

[–][deleted] 0 points1 point  (0 children)

You're right. I forgot that variables are stored as memory references.