[python] Python: Passing variables between functions

I've spent the past few hours reading around in here and elsewhere, as well as experimenting, but I'm not really understanding what I am sure is a very basic concept: passing values (as variables) between different functions.

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

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()

Based on my understanding of what function arguments do, 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, this is obviously a faulty understanding. My output is:

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

So, since "return" obviously does not do what I think it does, or at least it does not do it the way I think it should... what does it actually do? Could you please show me, using this example, what I would have to do to take the list from defineAList() and use it within useTheList()? I tend to understand things better when I see them happening, but a lot of the examples of proper argument-passing I've seen also use code I'm not familiar with yet, and in the process of figuring out what's going on, I'm not really getting a handle on this concept. I'm using 2.7.

ETA- in the past, asking a similar question, it was suggested that I use a global variable instead of just locals. If it will be relevant here also- for the purposes of the class I'm taking, we're not permitted to use globals.

Thank you!

This question is related to python function arguments

The answer is


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()) 

Your return is useless if you don't assign it

list=defineAList()

return returns a value. It doesn't matter what name you gave to that value. Returning it just "passes it out" so that something else can use it. If you want to use it, you have to grab it from outside:

lst = defineAList()
useTheList(lst)

Returning list from inside defineAList doesn't mean "make it so the whole rest of the program can use that variable". It means "pass this variable out and give the rest of the program one chance to grab it and use it". You need to assign that value to something outside the function in order to make use of it. Also, because of this, there is no need to define your list ahead of time with list = []. Inside defineAList, you create a new list and return it; this list has no relationship to the one you defined with list = [] at the beginning.

Incidentally, I changed your variable name from list to lst. It's not a good idea to use list as a variable name because that is already the name of a built-in Python type. If you make your own variable called list, you won't be able to access the builtin one anymore.


You're just missing one critical step. You have to explicitly pass the return value in to the second function.

def main():
    l = defineAList()
    useTheList(l)

Alternatively:

def main():
    useTheList(defineAList())

Or (though you shouldn't do this! It might seem nice at first, but globals just cause you grief in the long run.):

l = []

def defineAList():
    global l
    l.extend(['1','2','3'])

def main():
    global l
    defineAList()
    useTheList(l)

The function returns a value, but it doesn't create the symbol in any sort of global namespace as your code assumes. You have to actually capture the return value in the calling scope and then use it for subsequent operations.


passing variable from one function as argument to other functions can be done like this

define functions like this

def function1():
global a
a=input("Enter any number\t")

def function2(argument):
print ("this is the entered number - ",argument)

call the functions like this

function1()
function2(a)

Read up the concept of a name space. When you assign a variable in a function, you only assign it in the namespace of this function. But clearly you want to use it between all functions.

def defineAList():
    #list = ['1','2','3'] this creates a new list, named list in the current namespace.
    #same name, different list!

    list.extend['1', '2', '3', '4'] #this uses a method of the existing list, which is in an outer namespace
    print "For checking purposes: in defineAList, list is",list
    return list

Alternatively, you can pass it around:

def main():
    new_list = defineAList()
    useTheList(new_list)

Examples related to python

programming a servo thru a barometer Is there a way to view two blocks of code from the same file simultaneously in Sublime Text? python variable NameError Why my regexp for hyphenated words doesn't work? Comparing a variable with a string python not working when redirecting from bash script is it possible to add colors to python output? Get Public URL for File - Google Cloud Storage - App Engine (Python) Real time face detection OpenCV, Python xlrd.biffh.XLRDError: Excel xlsx file; not supported Could not load dynamic library 'cudart64_101.dll' on tensorflow CPU-only installation

Examples related to function

$http.get(...).success is not a function Function to calculate R2 (R-squared) in R How to Call a Function inside a Render in React/Jsx How does Python return multiple values from a function? Default optional parameter in Swift function How to have multiple conditions for one if statement in python Uncaught TypeError: .indexOf is not a function Proper use of const for defining functions in JavaScript Run php function on button click includes() not working in all browsers

Examples related to arguments

docker build with --build-arg with multiple arguments ARG or ENV, which one to use in this case? How to have multiple conditions for one if statement in python Gradle task - pass arguments to Java application Angularjs - Pass argument to directive TypeError: method() takes 1 positional argument but 2 were given Best way to check function arguments? "Actual or formal argument lists differs in length" Python: Passing variables between functions Print multiple arguments in Python