Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python global list modification inside and outside of functions

Tags:

python

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.

like image 484
Jon Avatar asked Sep 13 '25 19:09

Jon


1 Answers

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:

  • Why am I getting an UnboundLocalError when the variable has a value?
  • Is the behaviour of Python's list += iterable documented anywhere?
like image 176
Ashwini Chaudhary Avatar answered Sep 15 '25 09:09

Ashwini Chaudhary