1

I know this has been documented somewhere on Stack Overflow, but I can't for the life of me find it... I'll be happy to accept any relevant links.

I have the following code:

class A:
    def __init__(self, x=[]):
        x += [1]
        print id(x), x

print "Try with default:"
a = A()
b = A()
c = A()
d = A()

print "Try with custom:"
a = A([1])
b = A([2])
c = A([3])
d = A([4])

Which generates the following output:

Try with default:
4342272584 [1]
4342272584 [1, 1]
4342272584 [1, 1, 1]
4342272584 [1, 1, 1, 1]
Try with custom:
4342456688 [1, 1]
4342456688 [2, 1]
4342456688 [3, 1]
4342456688 [4, 1]

Why is it when using the default constructor value, the array grows on each subsequent construction?

Dan
  • 1,258
  • 1
  • 10
  • 22
  • 3
    The words you're looking for are "Mutable Default Argument". Google it, or read, for example, ["Least Astonishment" in Python: The Mutable Default Argument](http://stackoverflow.com/questions/1132941/least-astonishment-in-python-the-mutable-default-argument). – agf Sep 01 '11 at 13:15
  • Perfect! Those were the words and link I needed. Thanks @agf! – Dan Sep 01 '11 at 13:29

1 Answers1

0

@agf came up with the link that answers the question: "Least Astonishment" and the Mutable Default Argument

The accepted response for that link points to the following useful explanation: http://effbot.org/zone/default-values.htm

Community
  • 1
  • 1
Dan
  • 1,258
  • 1
  • 10
  • 22