Search code examples
pythonglobal-variables

Global List not made global


Excerpt of my code:

my_list = []

def scrape_the_web():
    # some code for scraping the web
    global my_list
    my_list.append(data scraped from web)

def print_list():
    print(my_list)     # Output []

Not sure why is it not working.


Solution

  • In your code, you never call scrape_the_web. This would work:

    my_list = []
    
    def scrape_the_web():
        global my_list
        my_list.append("x")
    
    def print_list():
        print(my_list)
    
    scrape_the_web()
    print_list()
    

    Update: BTW, since you don't change my_list but only append to it, the global is not strictly necessary, but it might make your code clearer.