How Do I fix an UnboundLocalError in Python 3?

1.5k views Asked by At
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?

3

There are 3 answers

5
Abhijith Asokan On

Because the statement todolist = todolist + [item], which is an assignment statement that creates a local variable todolist hides the global variable with the same name. So you have to specify that the variable is in global scope using the keyword global.

def add_item(item):
    global todolist
    todolist =  todolist + [item]

When you use append(),

 todolist.append(item)

there is no assignment operation, hence no variable is created and the variable in the global scope is used.

3
Sumit S Chawla On

Check the code below:

todolist = []

def add_item(item):
    global todolist
    todolist = todolist + [item]

def main():
    add_item(1)
    print(todolist)


if __name__ == '__main__':
    main()
1
Yann Vernier On

Even if you fix the local variable issue, your code doesn't behave like list.append. append operates by stateful side effect, mutating the list it was run on; your code created a new list and assigned a name. The only way I can think of to mutate a list that way without using a named method is a slice assignment:

def myappend(intolist, newitem):
    intolist[len(intolist):] = [newitem]

But this obviously uses the len built in function, and the assignment is translated into a setitem call. It's possible to avoid using len, by using implicit bool and getitem calls. But the calls are still there; basically, only a program that performs no operations can run without calling built in functions.