Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python .pop() changes local list globally? [duplicate]

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)

OUTPUT

[1, 2, 3, 4, 5]

['WTF']

[1, 2, 3, 4]

like image 800
Beatrix Kidco Avatar asked Apr 21 '26 02:04

Beatrix Kidco


2 Answers

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
like image 76
heemayl Avatar answered Apr 22 '26 15:04

heemayl


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.

like image 28
Christian Dean Avatar answered Apr 22 '26 15:04

Christian Dean



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!