0

Executing the following code:

def foo(b=[]):
    b.append(1)
    print(b)
foo()
foo()
foo()

The result is unexpectedly:

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

Investigating variable "b" memory address for different function calls:

def foo(b=[]):
    b.append(1)
    print(id(b))
foo()
foo()
foo()

returns the same value three times, whereas apparently variable initialization should create new [] object each time. Could you explain this to me please?

0 Answers0