todolist = []
def add_item(item):
todolist = todolist + [item]
def main():
add_item(1)
print(todolist)
if __name__ == '__main__':
main()
I am trying to make a function called add_item() which works like append() and I am not allowed to use any built in functions. I keep getting an UnboundLocalError. How would I fix this?
Because the statement
todolist = todolist + [item]
, which is an assignment statement that creates a local variabletodolist
hides the global variable with the same name. So you have to specify that the variable is in global scope using the keywordglobal
.When you use
append()
,there is no assignment operation, hence no variable is created and the variable in the global scope is used.