1
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?

blazing
  • 557
  • 2
  • 4
  • 20
  • Your constraints are weird. All operators including object creation are effectively built in functions, and Python is an imperative language to the degree that even `def` is an executable statement. `global` is a rare exception in that it's a declarative directive for the compiler. – Yann Vernier Nov 18 '17 at 14:54

3 Answers3

1

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.

Yann Vernier
  • 15,414
  • 2
  • 28
  • 26
  • Hey I just made a function call size() that returns the size of the list instead of using len, and thanks very much. – blazing Nov 18 '17 at 15:39
0

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.

Abhijith Asokan
  • 1,865
  • 10
  • 14
-1

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()
Sumit S Chawla
  • 3,180
  • 1
  • 14
  • 33