Search code examples
python-2.7instance-variables

Why does an instance variable, which is a list, grow in a for loop?


In the code below, I am expecting that a new instance of MyClass with the name 'obj' will be created every time inside the for loop. Therefore, the output should be [1] every time. But obj.mylist seems to grow. What am I missing?

class MyClass:
    def __init__( self, mylist_=[] ):
        self.mylist = mylist_ 

    def addData( self ):
        self.mylist.append( 1 )

for i in range(5):
    obj = MyClass()
    obj.addData()
    print obj.mylist

The output is:

[1]
[1, 1]
[1, 1, 1]
[1, 1, 1, 1]
[1, 1, 1, 1, 1]

Solution

  • Long story short, default values for arguments are created once at the time that the statement that defines the function is executed.

    Please refer to the official documentation:

    The default values are evaluated at the point of function definition in the defining scope, so that…

    <…>

    Important warning: The default value is evaluated only once. This makes a difference when the default is a mutable object such as a list, dictionary, or instances of most classes.

    <…>

    4.7.1. Default Argument Values — Python 3.5.2 documentation.

    This reference also contains the example of not following the warning — a very similar case and observed behavior.

    Additional references: