Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python weird thing with list local and global scope

Tags:

python

scope

list

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
like image 610
Artyom Avatar asked Feb 28 '26 09:02

Artyom


1 Answers

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.

like image 134
tdelaney Avatar answered Mar 01 '26 23:03

tdelaney



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!