Increment Variable Name

Pablo Ziliani pablo at decode.com.ar
Wed Jan 23 18:05:01 EST 2008


Hi David,

David Brochu wrote:
> I know the length of a list and I want to pass each element of a list  
> to a unique variable, thus I want to increment variable names. If the  
> list length = 4, i want to have the following variables: var1, var2,  
> var3, var4.

yuck... no, believe me, you probably don't want to do that.
Why don't you tell us what you are actually trying to achieve instead? 
(I mean, the problem, not the solution)


if you are REALLY sure that you want is what you asked:

 >>> for var in enumerate(['welcome', 'to', 'php']):
...     exec "var%s=%r"% var
...
 >>> vars()
{'var1': 'to', 'var0': 'welcome', 'var2': 'php', '__builtins__': <module 
'__builtin__' (built-in)>, 'var': (2, 'php'), '__name__': '__main__', 
'__doc__': None}

(I'm assuming that you have builtin objects in your list)
This is completely unsafe and error prone. IOW horrible.

HTH,
Pablo



More information about the Python-list mailing list