Warm tip: This article is reproduced from stackoverflow.com, please click
function python python-3.x methods

What causes the differing behavior in processing list parameters and dictionary parameters passed to

发布于 2020-03-27 10:25:09

When trying to use a function call to modify the value of a variable in the calling function, I observed the following difference in behavior when passing a list and set as function parameters.

#Passing list as parameter
def fun(a):
    a = a.append(13)

a = [12]
print(a)
fun(a)
print(a)

#Output
[12]
[12, 13]
#Passing set as a parameter
def fun(a):
    a = a.union({13})

a = {12}
print(a)
fun(a)
print(a)

#Output
{12}
{12}

My question is, why is the changes from the function carried over to the calling function when using a list but not when using set even though they are both of mutable data types?

Questioner
Tabish Mir
Viewed
75
khelwood 2019-07-03 22:47

The operations you are comparing are not equivalent.

alist.append alters the list at alist (and returns None).
aset.union creates a new set but doesn't modify the original.

If you did aset.add(13) that would be the set equivalent of alist.append(13) (adding a new element to an existing collection).
If you did alist = alist + [13] that would be the list equivalent of aset = aset.union({13}) (creating a new collection containing extra elements).