2

I was checking tiny scripts and noticed this:

def foo( a = [] ):
    a += [1]
    print(a)


foo() # prints [1]
foo() # prints [1,1]
foo() # prints [1,1,1]

Why does this happen instead of printing only [1]?

iam_agf
  • 639
  • 2
  • 9
  • 20
  • 2
    This has been answered many times https://stackoverflow.com/questions/1132941/least-astonishment-and-the-mutable-default-argument – jprebys Oct 20 '22 at 19:23
  • 1
    This is one of the tricky sharp edges in Python. When you create your function, it creates an empty list object, and your default parameter is that SPECIFIC list object. Every time you change it, the changes accumulate. The right solution is `def foo( a=None):` and `if a is None:` / `a = []`. – Tim Roberts Oct 20 '22 at 19:24

1 Answers1

-3

You basically append element to your list. For example [1] + [1] would be [1, 1].

learner
  • 603
  • 1
  • 3
  • 15