0

From the following code, I wish for the output of names to contain an array of names taken from a column in a csv file. When the function is run, the array remains empty. Why?

def cp_identifier():
    global names
    names = []
    array_dec()
    print(names)

def array_dec():
    with open("card_list_currents.csv", "r") as file:
        card_list_table = csv.DictReader(file, delimiter=',')
        for row in card_list_table:
            names.append(row["Card Name"])

Current Output:

[]

Expected output:

['Card Name', 'Card Name', ... , 'Card Name']
Jeril
  • 7,858
  • 3
  • 52
  • 69

3 Answers3

5

Why dont you use something like the following, rather than using a global variable

def cp_identifier():
    names = array_dec()
    print(names)
    return names

def array_dec():
    names = []
    with open("card_list_currents.csv", "r") as file:
        card_list_table = csv.DictReader(file, delimiter=',')

        for row in card_list_table:
            names.append(row["Card Name"])
    return names
if __name__ == "__main__": 
    names = cp_identifier()
    print(names)
Jeril
  • 7,858
  • 3
  • 52
  • 69
  • the question contains `cp_identifier` as the function name – Jeril May 27 '19 at 05:30
  • It still returns an empty array –  May 27 '19 at 05:31
  • how do you call the `cp_identifier` function – Jeril May 27 '19 at 05:32
  • if __name__ == "__main__": cp_identifier() –  May 27 '19 at 05:33
  • I have revised the solution, can you check now. Let me know if you not getting the desired output – Jeril May 27 '19 at 05:35
  • The array is still empty. I'm trying to make the array global because I have another function that is comparing a string to the string elements inside the array. It seems to work when I include opening the csv in the function where I compare the strings but I don't want to have the script opening the csv everytime I want to compare strings. I was trying to store the elements into an array which I can instead use to compare the string with –  May 27 '19 at 05:39
  • can you share the entire code, – Jeril May 27 '19 at 05:41
2

If you really need to use a global variable then following is a better way to declare global names

global names

def cp_identifier():
    #global names
    names = []
    array_dec()
    print(names)

def array_dec():
    with open("card_list_currents.csv", "r") as file:
        card_list_table = csv.DictReader(file, delimiter=',')
        for row in card_list_table:
            names.append(row["Card Name"])
Umair
  • 336
  • 1
  • 16
0

Because names is global to cp_identifier but not to array_dec. In the latter names is a local variable that is thrown away after the call.

However, avoid globals whenever possible. You can just return the names array from array_dec.

Torben Klein
  • 2,943
  • 1
  • 19
  • 24