0

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 = "temp1", I want to create a list called temp1. Obviously, in my case, I would not know what the value of s will be.

0

2 Answers 2

9

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.

Sign up to request clarification or add additional context in comments.

Comments

1

You can use globals():

>>> strs = "temp1"
>>> globals()[strs] = []
>>> temp1
[]

But using a dict for such purpose would be more appropriate:

>>> dic = {strs:[]}
>>> dic["temp1"]
[]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.