Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python

Received Error: UnboundLocalError: local variable 'shopping_list' referenced before assignment

while creating this function I received the error in the subject line.

def add_to_list(item):
    shopping_list = shopping_list.append(item)
    print("{} has been added to the list! There are {} items in the list.".format(item, len(shopping_list)))

I see where I went wrong. I should have stated:    

shopping_list.append(item)

But why is the line shown below incorrect? and what is the error referring to?

shopping_list = shopping_list.append(item)

thanks

2 Answers

Chris Freeman
MOD
Chris Freeman
Treehouse Moderator 68,453 Points

Hey Christopher Rodriguez, good question!

The object shopping_list is defined outside the function and is seen as a global from within the function. This changes as soon as an assignment to shopping_list is made within the function. When this is seen by the parser, shopping_list is added to the local namespace and the global version is no longer seen.

Now when shopping_list.append() is run, it is appending to the local shopping_list that has yet to be defined.

This is the same error as went there is a, say, global count variable and count += 1 is used inside a function. count becomes local and hence the right side of count + 1 has an undefined "count".

Post back if you have more questions. Good luck!!

I think I understand. so what I am saying in the following line...

shopping_list = shopping_list.append(item)

is...

(Local) shopping_list = (local) shopping_list.append(item)

As opposed to ...

(global) shopping_list.append(item)

Is that correct? Thank you!

Chris Freeman
Chris Freeman
Treehouse Moderator 68,453 Points

Correct. Once shopping_list is deemed β€œlocal”, all references to it become local.

The kicker is the list.append() method returns None so after the append, None is would be assigned to shopping_list and losing the list.

>>> lst = [1, 2, 3]
>>> lst = lst.append(4)
>>> lst == None
True