I have a variable with a string value in it.
I want to create a list with the value as its name/identifier, then append values to the list.
So assuming variable s = \"
You can use globals()
:
>>> strs = "temp1"
>>> globals()[strs] = []
>>> temp1
[]
But using a dict for such purpose would be more appropriate:
>>> dic = {strs:[]}
>>> dic["temp1"]
[]
Don't. Creating dynamic variables is rarely a good idea, and if you are trying to create local names (inside a function), difficult and greatly affects performance.
Use a dictionary instead:
lists = {}
lists[strs] = []
lists[strs].append(somevalue)
Namespaces are just default dictionaries for code to look up names in. It is a lot easier and cleaner to create more such dictionaries.
You can still access the global (module namespace with the globals() function, which returns a (writable) dictionary. You can access the function local namespace with locals(), but writing to this usually has no effect as local namespace access in functions has been optimized.
In Python 2 you can remove that optimisation by using a exec
statement in the function. In Python 3, you can no longer switch off the optimisation as the exec
statement has been replaced by the exec() function, which means the compiler can no longer detect with certainty that you are potentially writing to the local namespace with it.