[Tutor] variable name based on variables (expansion?)

Bill Mill bill.mill at gmail.com
Mon Feb 28 16:38:40 CET 2005


John,

On Mon, 28 Feb 2005 06:05:44 -0800 (PST), John Christian
<potus98 at yahoo.com> wrote:
> a python 2.3 noob asks:
> 
> # I have some lists
> GameLogic.varList0=[1,1,1,1]
> GameLogic.varList1=[1,1,1,1]
> GameLogic.varList3=[1,1,1,1]
> 
> # I want to change specific list elements
> GameLogic.varList0[2]=0
> print GameLogic.varList0
> [1,1,0,1]
> 
> # But I want the assignment
> # to be based on variables
> LIST=1
> POSITION=2
> 
> GameLogic.varList$LIST[$POSITION]=0
> 

Most likely you want to have a 2-dimensional list. Like so:

#note the lists inside a list
GameLogic.varMatrix=[[1,1,1,1],
[1,1,1,1], 
[1,1,1,1]]

Then, to get to the second element in the first list, do:

GameLogic.varMatrix[0][1]

Or the third element of the second list:

GameLogic.varMatrix[1][2]

In general, using zero-based counting of rows and columns, accessing
the array is done with:

GameLogic.varMatrix[row][column]

so access like you have above is just:

GameLogic.varMatrix[LIST][POSITION]

Assuming that LIST and POSITION are zero-based counts.

Also note that all-CAPS variables in python are traditionally used
only for constants. This is a pretty strong tradition which, if you
break, will confuse anyone trying to read your code. Variables are
traditionally either camel case or all lower-case with underscores.

> # But the variable assignment above does not work.
> # Python complains of a syntax error.
> # I've also tried variations of eval(), single ticks,
> # back ticks, quotes, etc... but I just can't seem
> # to get the syntax right.
> #
> # Can someone please provide a working example?
> 

the $ is not a syntactic character in python. Single quotes simply
delimit strings in python. Back ticks are equivalent to the str()
function which creates strings (or is it repr()? I can't remember;
it's generally bad form to use back ticks anyway). Double quotes are
the same as single quotes.

Please read the tutorial at http://docs.python.org/tut/tut.html .

Peace
Bill Mill
bill.mill at gmail.com


More information about the Tutor mailing list