How to convert a list of strings into a list of variables

Nobody nobody at nowhere.com
Thu Aug 18 20:45:28 CEST 2011


On Thu, 18 Aug 2011 16:09:43 +0000, John Gordon wrote:

>> How would you convert a list of strings into a list of variables using
>> the same name of the strings?
> 
>> So, ["red", "one", "maple"] into [red, one, maple]
> 
> If the strings and the object names are exactly the same, you could use
> eval().

Eval is overkill for variables; use globals() and/or locals().

But data which is supposed to be indexed by a variable key (i.e. a name
which is determined at run-time) should normally be put into a dictionary.
If access with fixed keys is far more common than variable keys, using an
object (with getattr/setattr for variable keys) may be preferable.





More information about the Python-list mailing list