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 Python Collections (2016, retired 2019) Lists Shopping List Take Three

Dongyun Cho
Dongyun Cho
2,256 Points

global keyword for shopping_list?

hi, it seems shopping_list variable is being used all over the functions in this project, shopping list 3. but I've heard that I need to use global variable with global keyword when I need to use this in other funtion. Like this?

def add_to_list(item):  
global shopping_list

but in this course, global keyword shows just nowhere. am I knowing wrong? or how can any problem show up yet without global keyword?

1 Answer

andren
andren
28,558 Points

The global keyword is needed if you want to assign a new value to a global variable within a function, but it is not needed to simply read the contents of a global variable.

In addition operations like append and insert which you might think would count as changing the variable actually do not. This is because they don't actually change what the variable is assigned to. It's still assigned to the same list instance, the list in questions just has some of its content changed.