Search code examples
pythonlistgloballocal-variables

how can i make a list inside a function global?


in this function, I have a list I want to make global and allow access to outside the function:

def get_data():
    d = client_socket.recv(BUFSIZ)
    feed = pickle.loads(d)

    number_authorized = []
    for q in feed:
        number_authorized.append(q[0]) 
    number_authorized.sort()

This number_authorized list changes each time the function get_data() is called. I want the global number_authorized list to change according to the changes inside the function.

How can I allow access to the list and its values outside the function? Do I have to state global number_authorized every time I try to change or access the list's values?

I'd really appreciate it if you could help me!!! :)


Solution

  • Just declare that:

    def get_data():
        d = client_socket.recv(BUFSIZ)
        feed = pickle.loads(d)
    
        global number_authorized #declaration
    
        number_authorized = []
        for q in feed:
            number_authorized.append(q[0]) 
        number_authorized.sort()