0

Can someone please explain the following to me:

class C:
    def __init__(self, lst=[]):
        self.lst = lst
        self.i = 1

    def foo(self):
        self.lst.append(self.i)
        self.i += 1

def main():
    a = C()
    b = C()
    a.foo()
    print(a.lst, a.i)
    print(b.lst, b.i)

main()

I expect the output to be:

[1] 2
[] 1

since each instance of C has it's own instance of lst, but it is

[1] 2
[1] 1

which seems to me to be not only wrong, but also inconsistent (i is not common, lst is). Huh?

Baruch
  • 20,590
  • 28
  • 126
  • 201
  • This is likely of interest to you: http://stackoverflow.com/questions/1132941/least-astonishment-in-python-the-mutable-default-argument –  Jun 03 '15 at 17:50
  • Your confusion is a result of the part where you think that "each instance of C has it's own instance of `lst`". In some languages that may be true, but not in Python... – twalberg Jun 03 '15 at 19:05

0 Answers0