0

First question here, thanks for reading.

In Python you cannot change global variables within a function without first using global, but you can do that with lists. What is exactly going on? Lists are assigned to a variable as well, right?

Examples:

Global variable

a = 1
def add_1():
  a += 1
add_1()

--->"UnboundLocalError: local variable 'a' referenced before assignment"

Global list

b = ["a", "b"]
def appnd_1():
  b.append("c")
appnd_1()
print(b)

--->"['a', 'b', 'c']"

Thanks!

  • In the first example, you are assigning a new value to the variable `a`. In the second example, you are simply *modifying the contents* of variable `b`. You are not assigning a new value. – larsks Apr 20 '21 at 11:49
  • "In Python you cannot change global variables within a function without first using global, but you can do that with lists." What you must understand is that *variables have scope, not objects*. You can mutate an object *anywhere you can reference it*. Of course, references in *any scope will see that mutation*. You can never *assign* to a global *variable* in a local scope without using a `global` statement. – juanpa.arrivillaga Apr 20 '21 at 11:50

0 Answers0