0

At the top of my python file, I create a list:

table = [[]]

Then I have a method, that sets the value of the list:

def setTable():
    table = list(csv.reader(open("vplan/temp.csv")))
    print(table)

If I run it, the value of table gets printed out, as it should be. However, if I try to print it outside of my method

print(table)

It only prints "[[]]" - I dont understand why. I hope someone can explain this to me, I don't use Python very often.

Tomas Wilson
  • 147
  • 2
  • 7
  • 5
    Because you simply assign the result to `table` inside `setTable`, which is a local variable. You could use a `global` statement, but rather, you should simply `return` the result from your function – juanpa.arrivillaga Nov 06 '18 at 19:25

2 Answers2

0

The table variable inside your method is not the same as the one outside of your method in order to use the same one try doing this:

table = [[]]

def setTable(table):
    table = list(csv.reader(open("vplan/temp.csv")))
    return table

print(setTable(table))

I hope this helped for you I do a lot f python programming, so I am pretty familiar with the language. I am not sure about when you are defining the table variable in the beginning that you need to assign it like this: [[]], but if that's how you need your code to be to work then use it like that. If it doesn't work with it like this: [[]], then try it like this: []. I hope this helped you, thanks.

0

According to the LEGB scope rule (which you can read here: https://realpython.com/python-scope-legb-rule/#using-the-legb-rule-for-python-scope), the variable that you have created is at the Global Scope and the one inside the function is Local Scope.

You cannot access the Global Scope variable table inside the function by default (it creates a local scope variable with the same name that you can access within the function). Instead you have to tell python that you are trying to assign it to a global variable table.

So this is the code you need to write:

table = [[]]

def setTable():
    global table
    table = list(csv.reader(open("vplan/temp.csv")))
    print(table)

print(table)
zoomlogo
  • 173
  • 4
  • 14