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

Alan Gauld alan.gauld at freenet.co.uk
Mon Feb 28 22:19:39 CET 2005


> # I have some lists
> GameLogic.varList0=[1,1,1,1]
> GameLogic.varList1=[1,1,1,1]
> GameLogic.varList3=[1,1,1,1]

Pythonically:

GameLogic.varLists = [[1,1,1,1],
                      [1,1,1,1],
                      [1,1,1,1]]

> # But I want the assignment
> # to be based on variables
> LIST=1
> POSITION=2
> 
> GameLogic.varList$LIST[$POSITION]=0

GameLogic.varlists[LIST][POSITION] = 0

> # I've also tried variations of eval(), single ticks,
> # back ticks, quotes, etc... but I just can't seem
> # to get the syntax right.

You could use eval but its nasty and should be avoided if possible. 
Its usually better to eitrher use lists or dictionaries.

> # if I hardcode things, but I'd rather use variables
> # since I will eventually have 20 lists with at least
> # 10 positions in each list.

In that case using variables will be messy, far better to use 
a single variable which is a container. If for some reason 
your lists cannot be contigious then you should opt for a 
dictionary and manipulate the key names:

GameLogic.varLists = {'list0' : [1,1,1,1],
                      'list1' : [1,1,1,1],
                      'list3' : [1,1,1,1]}

key = 'list' + str(LIST)
GameLogic.varlists[key][POSITION] = 0

HTH,

Alan G
Author of the Learn to Program web tutor
http://www.freenetpages.co.uk/hp/alan.gauld


More information about the Tutor mailing list