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.

1
  • 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 Commented Nov 6, 2018 at 19:25

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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)

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.