[Tutor] Reference a variable from a string whose value is the name of the variable

Patrick Wheeler patrick.john.wheeler at gmail.com
Tue Jun 6 20:08:20 CEST 2006


>data = [ ]
>for i in xrange(1,101):
> data = data.append((f %i  _n, f %i_v))

The function locals() will return a dictionary of variables in the current
scope.  This can then be used to reference variables by name.
x=1
xname = 'x'
print locals()['x']
print locals()[xname]
This prints:
1
1

or for your example.
data = [ ]
for i in xrange(1,101):
    data = data.append
((locals()['f'+str(i)+'_n'],locals()['f'+str(i)+'_v']{}))

Hope this helps.

pjw
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060606/d71a4352/attachment.html 


More information about the Tutor mailing list