Simple python loop problem

for looper in range (numwords):
    var(eval('test_word%d_%d' % (looper, looper))) = 1

Numwords is already defined. I am attempting to use a different variable per loop. (test_word0_0 = 1, then test_word1_1 = 1…)

How do you call and edit and read a variable that is named depending on the loop?

Is this a universal solution? 

globals()['test_word%s_%s' % (looper, looper)] = 1

You should also know that in Python, iterating over integer indices is bad style, and also slower than the alternative. If you just want to look at each of the items in a list  or dict, loop directly through the list or dict.

mylist =[1,2,3]for item in mylist:print item mydict ={1:'one',2:'two',3:'three'}for key in mydict:print key, mydict[key]

This is actually faster than using the range(), and removes the extraneous i variable

1 Like