Search code examples
pythonfunctionscopereturn

How do I pass variables across functions?


I want to pass values (as variables) between different functions.

For example, I assign values to a list in one function, then I want to use that list in another function:

list = []

def defineAList():
    list = ['1','2','3']
    print "For checking purposes: in defineAList, list is",list
    return list

def useTheList(list):
    print "For checking purposes: in useTheList, list is",list

def main():
    defineAList()
    useTheList(list)

main()

I would expect this to do as follows:

  1. Initialize 'list' as an empty list; call main (this, at least, I know I've got right...)
  2. Within defineAList(), assign certain values into the list; then pass the new list back into main()
  3. Within main(), call useTheList(list)
  4. Since 'list' is included in the parameters of the useTheList function, I would expect that useTheList would now use the list as defined by defineAList(), NOT the empty list defined before calling main.

However, my output is:

For checking purposes: in defineAList, list is ['1', '2', '3']
For checking purposes: in useTheList, list is []

"return" does not do what I expected. What does it actually do? How do I take the list from defineAList() and use it within useTheList()?

I don't want to use global variables.


Solution

  • This is what is actually happening:

    global_list = []
    
    def defineAList():
        local_list = ['1','2','3']
        print "For checking purposes: in defineAList, list is", local_list 
        return local_list 
    
    def useTheList(passed_list):
        print "For checking purposes: in useTheList, list is", passed_list
    
    def main():
        # returned list is ignored
        returned_list = defineAList()   
    
        # passed_list inside useTheList is set to global_list
        useTheList(global_list) 
    
    main()
    

    This is what you want:

    def defineAList():
        local_list = ['1','2','3']
        print "For checking purposes: in defineAList, list is", local_list 
        return local_list 
    
    def useTheList(passed_list):
        print "For checking purposes: in useTheList, list is", passed_list
    
    def main():
        # returned list is ignored
        returned_list = defineAList()   
    
        # passed_list inside useTheList is set to what is returned from defineAList
        useTheList(returned_list) 
    
    main()
    

    You can even skip the temporary returned_list and pass the returned value directly to useTheList:

    def main():
        # passed_list inside useTheList is set to what is returned from defineAList
        useTheList(defineAList())