2I'm relatively new to Python (using 3.3.3) and have a list related question. When modifying a global list variable inside a function (please, no lectures on the evils of global variables), you typically do not need to declare the list with the global keyword inside the function - provided you stick to list methods. In particular, you may not use augmented addition without first using the global keyword. What surprises me is that using augmented addition outside the function clearly isn't modifying the list variable (only the list contents), and so I would expect to be allowed to use it inside a function without using the global keyword. Here are two examples that I can't reconcile:
list_1 = []
def my_func():
list_1.append(0)
#list_1 += [0]
my_func()
print('list_1 =', list_1)
This prints list_1 = [0]
, as expected, while the commented out augmented addition operation generates a complaint about using a local variable before assignment.
Here's an example that I can't reconcile with the previous one:
list_1 = [0]
list_2 = list_1
list_1 += [1]
print('list_2 =', list_2)
This prints list_2 = [0, 1]
, which suggests to me that list_1 += [1]
did not modify the list_1 variable. I'm aware that list_1 = list[1] + [1]
qualifies as modifying list_1, but augmented addition doesn't seem to. Why does augmented addition, inside a function, require use of the global keyword? Thanks for any help understanding this.
The problem is when a function body is parsed all the variables used in either normal assignments or augmented assigments are considered as local variables, so when the function gets called Python will not look for those variables in global scope hence it will raise an error. Hence you need to specify those variables as global
to tell Python to look for them in global scope.
Another alternative is to use list.extend()
instead of +=
.
Related:
UnboundLocalError
when the variable has a value?+=
iterable documented anywhere?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