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.

martineau
  • 119,623
  • 25
  • 170
  • 301
TheQuantumMan
  • 257
  • 1
  • 3
  • 10
  • You can check [here](https://stackoverflow.com/questions/1373164/how-do-i-create-variable-variables) – Girish Srivatsa Mar 02 '21 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]`. – TheQuantumMan Mar 02 '21 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? – Girish Srivatsa Mar 02 '21 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 – TheQuantumMan Mar 02 '21 at 16:04
  • Also see [Why you don't want to dynamically create variables](https://stupidpythonideas.blogspot.com/2013/05/why-you-dont-want-to-dynamically-create.html). – martineau Mar 02 '21 at 16:41
  • Your other question about joining many arrays with names like 'A_1','A_2' illustrates the problem with creating objects with 'dynamic' names. Not only is it a pain to create them, it is also a pain to use them. – hpaulj Mar 02 '21 at 17:21
  • @hpaulj Well, message received then! haha I guess I won't be using A_i. Cheers – TheQuantumMan Mar 03 '21 at 07:57

1 Answers1

-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.

carser
  • 1
  • 1
  • It's not only not recommended, much less "highly", the documentation for [`locals()`](https://docs.python.org/3/library/functions.html#locals) explicitly notes: "The contents of this dictionary should not be modified". – martineau Mar 02 '21 at 16:43
  • 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. – carser Mar 02 '21 at 18:00
  • 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). – martineau Mar 02 '21 at 18:18