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