简体   繁体   中英

Python weird thing with list local and global scope

Why can we modify list with the append method but can't do the same with the list concatenation ? I know about the local and global scope, I'm confused about why we can do it with append method, thanks in advance

some_list=[]

def foo():
    some_list.append('apple')


foo()
print(some_list)
#it works

with list concatenation

some_list=[]

def foo():
    some_list+=['apple']


foo()
print(some_list)
#UnboundLocalError: local variable 'some_list' referenced before assignment

Augmented operations like += reassign the original variable, even if its not strictly necessary.

Python's operators turn into calls to an object's magic methods: __iadd__ for += . Immutable objects like int can't change themselves so you can't do an in-place += like you can in C. Instead, python's augmented methods return an object to be reassigned to the variable being manipulated. Mutable objects like lists just return themselves while immutable objects return a different object.

Since the variable is being reassigned, it has to follow the same scoping rules as any other variable. The reassignment causes python to assume that the variable is in the local namespace and you need the global keyword to override that assumption.

Local and global scopes apply to the variable itself, specifically what object it is referencing. The variable just points to an object in memory. You can't change the 'pointer' of the variable in a different local scope, but you can change the object that it points to. Here, you can use append because it changes the list object itself, the one stored in memory. It doesn't change what the variable some_list points to. On the other hand, the second example, you try to reassign some_list to refer to a new list that was created in combination with the old list. Since this can't happen, the interpreter now treats this some_list as a local variable separate from the other, gloabl one

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM