Warm tip: This article is reproduced from serverfault.com, please click

Difference between list and char memory allocation

发布于 2020-11-30 14:15:23
def f(b, a=[]):
    a.append(b)
    print('a : ', a)
f(1)
f(2)

# >> a : [1]
# >> a : [1, 2]

I thought variable 'a' remained in memory because GC or Reference Count didn't activate.

def f(b, a=''):
    a += b
    print('a : ', a)

f('1')
f('2')

# >> a : 1
# >> a : 2

result of this function is different. variable a initialized each time of calling function.

memory of dictionary, set, list were remained after calling function. but int, string was cleared. is it different memory allocation system?

Questioner
PSW
Viewed
0
Aaj Kaal 2020-11-30 22:36:45

The reason is list is a mutable object. On the first call a is initialized and in subsequent calls it is referenced. int and str are immmutable as you can see from below:

>>> str1 = 'hello'
>>> id(str1)
1900958690736
>>> str1 = 'how r u'
>>> id(str1)   # is a different string now
1900958712176

In order to achieve what you are looking for you can use:

def f(b, a=None):
    if not a:
        a = []
    a.append(b)
    print('a : ', a)
f(1) # a :  [1]
f(2) # a :  [2]