Dominik Praski
Dominik Praski

Reputation: 31

trying to get a list from one sub routine to another

I'm creating a list from data from a file and i cant use the list out side its original subroutine how can i just make it global so i can use it and change it anywhere i want ?

def selecting_qs():
    global main_list
    dif = difficulty.get()
    print(main_list,dif)


#main list order:
#Question ID  ,  Difficulty  ,  Topic  ,  Answer ID  ,  Picture ID  ,  Frequency 
def main_file_info():
    main_file = open("main_file.txt","r")
    main_file_info=main_file.readlines()
    for line in main_file_info:
        main_list=line.split("@")

    main_list=main_list[1:len(main_list)-1]
    main_file.close()

    return(main_list)

Upvotes: 1

Views: 33

Answers (1)

Ma0
Ma0

Reputation: 15204

To pass variables used in functions around, you just have to return them, assign them and well.. pass them. On your current script, this would look as follows:

def selecting_qs(a_list):
    # global  <-- main_list this is not needed and can lead to problems!
    dif = difficulty.get()
    print(a_list, dif)


#main list order:
#Question ID  ,  Difficulty  ,  Topic  ,  Answer ID  ,  Picture ID  ,  Frequency 
def main_file_info():
    main_file = open("main_file.txt","r")
    main_file_info=main_file.readlines()
    for line in main_file_info:
        main_list=line.split("@")

    main_list=main_list[1:len(main_list)-1]
    main_file.close()

    return main_list  # returning the item(s) thus making them accessible from the outer scope

my_main_list = main_file_info()  # assigning the item(s) to a variable
selecting_qs(my_main_list)  # passing the item(s) to another function

If there are outstanding questions, please let me know.

Upvotes: 1

Related Questions