0

I have a list including some names, as example: data_set_names=['matrix_1','matrix_2','matrix_3']. Inside a loop, I want to use each of these names for storing the output of some computations, which are as NumPy array. I highly appreciate if someone could tell me how to do that. As I looked it up online, exec() function can be used to convert a string to a variable name, but in my case, it is not useful.

2
  • Would storing the matrices as values in a dictionary where the keys are the strings in the list work for you? Commented Jul 30, 2021 at 10:34
  • Does this answer your question? How do I create variable variables? Commented Jul 30, 2021 at 11:17

2 Answers 2

1

You can use the dictionary of str/numpyArray

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

Comments

0

You could think about using globals() or locals() depending on your needs. Both are a dictionary of the variables you are using in your code, (global or locals) and from there you can assign a variable as a string, in your case something like:

for i in data_set_names:
    globals()[i] = 'your data here'

2 Comments

So why not use an explicit dictionary rather than doing this weird stuff?
Thank you for your suggestion. Indeed, as I tried using a Dictionary is much easier.

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.