0

I ran the following small code

def func2(xxx=[]):
        xxx.append(1)
        print xxx
        return None
func2()
func2()
func2()

The output is the following:

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

Which variable does the program save those lists [1], [1,1],[1,1,1] in? Why doesn't the computer clear the memory allocated to the function after the function is executed?

I also tried the following function

def func(x=2):
        print 'at the beginning of the function x = ', x
        x=x+1
        print 'after the value is changed x = ', x
        return x
func()
func()
func()

The output is the following:

at the beginning of the function x =  2
after the value is changed x =  3
at the beginning of the function x =  2
after the value is changed x =  3
at the beginning of the function x =  2
after the value is changed x =  3

And it turns out that this function performs normally. What's the major difference between func and func2?

Yicun Zhen
  • 139
  • 1
  • 10
  • To put is simply, a new list is not created each time `func2()` is called. `xxx` is the same list each time `func2()` is called. Python only creates the `xxx` list _**once_** during import time, and `xxx` is the same list used throughout the program. – Christian Dean Jun 12 '17 at 19:59
  • @ChristianDean I tried a similar function where the default argument is a number. And there is no such behavior. I have added the detail to the original question. – Yicun Zhen Jun 12 '17 at 20:46
  • That is because a list is mutable - that is, it can be modified after creation - while and integer object is immutable. – Christian Dean Jun 12 '17 at 21:12
  • @ChristianDean what's the motivation of making list a mutable object? – Yicun Zhen Jun 12 '17 at 22:30
  • The motivation is that programmers needed and still do need an object with container-like properties from which you can easily add, remove, and keep track of many data. – Christian Dean Jun 13 '17 at 13:56

0 Answers0