Are you sure you want to put a bunch of variables in a list, or do you just want a list? You could do this:
1 |
myvars = [var_one, var_two,... var_nine]
|
But that is identical to :
1 |
my_vars = [ 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 ]
|
By identical I mean the list will contain the value of these variables, because these variables are immutable (cannot be changed). If, after creating the list, I did this:
Now var_1 == 101, but my_list[0] == 1. The reason for this is obvious and completely unclear depending on how long you have been writing python
When you type "var_one = 1" you are not telling python "I want to use the name "var_one" to mean 1. Python adds the name and value to a dictionary so it can look up the value if you reference "var_one" elsewhere in your program. When you add "var_one" to a list Python says "Ah! someone wants to know what var_one means. I will look it up and return the value I have saved". So the thing that gets added to the list is the value Python has saved for var_one. If later on I type "var_one = 2", Python does the same 'save the value referenced by a name' thing. This time Python sees that "var_one" is already in the dictionary, so it reuses the name and saves the new value.
That's why I am a little confused when you ask to add a bunch of variables to a list. Why do that? There are valid reasons. For example I might save a bunch of variables to a list as a kind of shapshot. The values in the list would not change, even if the variables used to create the list do.
Another reason for creating a list of variables is that the variables are mutable. A mutable object does not change, but it's value does. A list is mutable If I do this:
1 2 3 |
mylist = [ 1 , 2 , 3 ]
mylist.append( 4 )
mylist.remove( 2 )
|
mylist is the same "variable" after each of the commands is executed. If you look in the python dictionary under "mylist" you will see the identifier for the list (essentially his storage location) is unchanged. What does change with each command is the value(s) stored inside mylist.
A list of mutable variables can be a nice way to organize your code. Earlier there was a question on the forum about finding available choices for each square in sudoku puzzle. The standard sudoku puzzle has 81 mutable variables, one for each "cell" in the 9x9 sudoku board. The sudoku program used a list for each row in the puzzle and another array to hold all the lists. Thus the sudoku board could be stored as a list of mutable objects, and it was a lot easier to look at a cell using cell[row][col] than having 81 variables named cell11, cell12...
What are you planning to do with your list of variables?