1

I want to run a for loop with index i so that I can define (inside each loop) an ndarray with name A_i. More concretely, I want it to look something like

for i in range(numer):
    A_i = M

where M is some ndarray that was defined in a previous step. The way I'm looking for is probably something reminiscent of the .format() method that works for strings.

7
  • You can check here Commented Mar 2, 2021 at 16:00
  • @GirishSrivatsa I tried it out both with lists and dictionaries, but it makes more sense (for the code i'm writing) to have these objects as, say, A_i, rather than, say, A[i]. Commented Mar 2, 2021 at 16:02
  • Yes there is a method given below to create based on globals or the one based on exec.Both of them should be fine? Commented Mar 2, 2021 at 16:03
  • @GirishSrivatsa yeah, but people there comment that that's not recommended. But if it's the only way, it'd do I guess Commented Mar 2, 2021 at 16:04
  • Also see Why you don't want to dynamically create variables. Commented Mar 2, 2021 at 16:41

1 Answer 1

-1

You can create all objects using globals() or locals() methods, depending if you want your objects to have global or local scope.

for i in range(10):
    globals()[f'A_{i}'] = M

for i in range(10):
    locals()[f'A_{i}'] = M

Still, this isn't a highly recommended practice.

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

3 Comments

It's not only not recommended, much less "highly", the documentation for locals() explicitly notes: "The contents of this dictionary should not be modified".
I agree. In fact, I point out in my answer that it’s a non-recommended practice. However, I consider appropriate to theorize about it and expose the different possibilities that language offers.
Guess we disagree. I don't think showing folks how not to do things is very helpful or enlightening—there's plenty of that kind of stuff this site already without your "contribution". There's also the fact that dynamically creating variables, by any means, is a poor programming practice unto itself (which you would know if you'd read any of the linked questions and articles about why that's the case).

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.