59

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.

0

8 Answers 8

68

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()) 
Sign up to request clarification or add additional context in comments.

Comments

14

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.

1 Comment

Thank you- I appreciate that you provided not only an example, but an explanation of why it works that way.
4

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 the value of 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.

1 Comment

" It means "pass this variable out and give the rest of the program one chance to grab it and use it"." No; it means "pass this value out". There needn't be a variable at all. That's the underlying issue.
2

Your return is useless if you don't assign it

list=defineAList()

Comments

1

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)

1 Comment

The more relevant concept is scope, not namespaces. In Python, a "namespace" is represented by the attributes of an object or the keys of a dictionary. This includes the globals() and locals() dictionaries, but it also includes, for example, the contents of a module or package.
1

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)

5 Comments

Indentation is quite off, that should be fixed first. Secondly, since you are specifying global a, there is no need for a return statement in function1(). It is explicitly bad taste to use global variables in general, but completely unwarranted in such a simple application. Cf. this.
@N.Wouda how can i perform such operation without using global?
def function1(): return input("Enter any number\t"). Then, a = function1() and function2(a). Of course, you should apply proper formatting of this code, but that's impossible for me to achieve in a comment.
i must say this just saved me from an app i was developing.the app requires auto creation of session file once a user is logged in and also deletes the file once the user is logged out. i was searching for solution to the logout issue until i stumbled upon this making local variable global and it actually helped and saved me today.Thannks for this.
@OlowuAbayomi Glad it helped!
0

Try do the following:

def funa():
    name=("Bob")
    age=("42")
    return name, age

def funb():
    name, age=funa()
    print(name)
    print(age)

funb()

Happens that you gotta call it via funa() instead of age.

Comments

0

Just return it.

Example:

def initiate_excel_corvert():
 
    df = pd.ExcelFile('empty_book.xlsx').parse('Sheet')
    x=[]
    x.append(df['Numbers'])
    x.clear()
    x.extend(df['Numbers'])
    print(len(x))
    print('\n')
    len_of_column_0 =+1 + len(x)
    print("+ add-on ::")
    print(len_of_column_0)
    print('\n')
    
    return render_template('index.html'), insert_into_excel(len_of_column_0)
    
def insert_into_excel(len_of_column_0):
    print ("len_of_column_0 = ", len_of_column_0)
    print('\n')

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.