List type global variable function modification problem.

the following two functions:

def func2(x):
    x[:len(x)] = list(set(x))
    return len(x)

-->L = [0,0,1,2,3]
-->func1(L)
4 
-->L
[0,0,1,2,3] -sharp l

-->func2(L)
4
-->l
[0,1,2,3] -sharp l

I know why func2 changes L, but I don"t know why func1 doesn"t change L.
I hope you can give me some advice. Thank you!

Nov.15,2021

first, you need to understand the behavior of assignment statements in python. Unlike the C language, [var=value] in python is read as "assign var variable tags to value objects", not the other way around.

>>> foo=[1,2,3]
>>> bar=foo
>>> id(foo), id(bar)
(2899313114056, 2899313114056)

the above code shows that the two variables have the same memory address, which is unthinkable in the C language. A variable in
python is just a name and does not have its own address, type, and value. It can only temporarily obtain the address, type, and value of the object by "attaching" to the object.

then, you have to understand that [Foo [index] = value] is not an ordinary assignment statement, but calls the foo.__setitem__ (index, value) method behind its back.

>>> foo, id(foo)
([1, 2, 3], 2899313114056)
>>> foo[0]=4
>>> foo, id(foo)
([4, 2, 3], 2899313114056)
>>> foo.__setitem__(0, 5)
>>> foo, id(foo)
([5, 2, 3], 2899313114056)

therefore, slice assignment statements can modify list objects, while ordinary assignment statements cannot modify list objects.


The

assignment operation produces a new object, but the L original object does not change. The
slicing operation operates on the original object, reassigning the L-meta-object.

def func1(x): 
    print(id(x))
    x = list(set(x))
    print(id(x))
    return len(x)

def func2(x):
    print(id(x))
    x[:len(x)] = list(set(x))
    print(id(x))
    return len(x)
   
L = [0,0,1,2,3]

call func1,func2 respectively to check the memory address of L

func1 assignment produces a new object

func1(L)

139912186104520
139912185279368
4
L
[0,0,1,2,3]

func2 slice, modify on the original object

func2(L)
139912186104520
139912186104520
4
L
[0, 1, 2, 3]
Menu