# 1st Method
a = ["b","x","k"]
a = "5"
print(a)
# 2nd Method
def add1(new):
a.append(new)
add1("X")
print(a)
# 3rd Method
def add2(new):
a = new
add2("Z")
print(a)
Function add2 looks almost similar to the 1st method in adding an item into a list, yet it produces an error "local variable referenced before assignment". What is the logic behind this error? How do we fix the error for function add2 without declaring variable 'a' as global?
CodePudding user response:
For lists, = extends. You can use a.extend(new).
CodePudding user response:
Add another parameter to your function and pass the list through that.
a = ["b", "x", "k"]
a = "5"
print(a)
# 2nd Method
def add1(new):
a.append(new)
add1("X")
print(a)
# 3rd Method
def add2(list_to_add, new):
list_to_add = new
add2(a, "Z")
print(a)
CodePudding user response:
The = operator is an augmented assignment operator. Since assignments make the target a local variable, so do augmented assignments.
def add2(new):
# v target a ...
a = new
# ^ ... is assigned to
Local variables are only read from the current scope; since there is no initial value for a in the function scope and thus nothing to add new to, an error is raised to indicate this.
If you want to use augmented assignment with a global variable, the only option is to declare the variable as global.
def add2(new):
global a
a = new
The various workarounds of avoiding augmented assignment, such as using the alternative list.extend, are merely different ways of modifying the content of a global variable. They do avoid the marker of the global keyword, but not the actual code smell of modifying globals.
The true alternative is not to refer to globals in any way during modifications:
def add(a, new):
a = new
