I came across a error in my code and after searching found that the .pop() function changes a list value in a local function, on a global level, without using return function or global statement. I understand what pop does, I've used it before, but I don't understand why it's affecting the value of list globally. Why is that? Is there a name for this and are there other functions that does the same?
#Example code
listname=[1,2,3,4,5]
def checkpop(listname):
popped = listname.pop()
listname = ['WTF']
print (listname)
print(listname)
checkpop(listname)
print(listname)
[1, 2, 3, 4, 5]
['WTF']
[1, 2, 3, 4]
Because assignments do not make any new copy of any object in Python. So, when you pass the global list as the argument to the function, you are binding to the same list object inside the function.
As lists are mutable in Python, when you do a in-place operation in it, you are changing the same global list object.
To get a better grasp, you can always check the id:
In [45]: lst = [1, 2]
In [46]: def foo(lst):
...: print(id(lst))
...: return
In [47]: id(lst)
Out[47]: 139934470146568
In [48]: foo(lst)
139934470146568
Your making a false distinction between the object the listname variable refers to and the object the listname parameter refers to.
The listname variable is like a tag. It is simply a reference to the list object [1, 2, 3, 4, 5]. When you passed listname into checkpop, you gave the listname parameter a reference to the same list object the listname variable refers to. The point here, is that the listname variable and the listname parameter point to the same object. Thus, mutating the object the listname parameter refers to, will also change the object that the global listname variable refers to.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With