0

I am currently trying to define a number of variables as empty lists (equal in quantity to the number of iterations of the loop). So far I've tried the following:

for i in [1,2,3]:
        locals()["temp_set_" + str(i)] = []

When I try to print(temp_set_1) outside of the loop in order to verify the output, I get the following error: NameError: global name 'temp_set_1' is not defined

I am not sure what I'm doing wrong at the moment and would appreciate it if someone could point me in the right direction.

najusten
  • 59
  • 6
  • 4
    Change `locals` to `globals`, but in general it is not a good idea to dynamically create variables. What is your use-case? – Tomerikoo Mar 02 '20 at 14:57
  • BTW this works for me with no errors. If you are running this loop from a function and trying to print outside of it, it will not work – Tomerikoo Mar 02 '20 at 15:12
  • Your `temp_set` has called, it said it wants to be a list one day. – Klaus D. Mar 02 '20 at 15:19

1 Answers1

0

In my mac, with python3.6, it works.

for i in [1,2,3]:
    locals()["temp_set_" + str(i)] = []

output result

Andy
  • 58
  • 7
  • This is more of a comment than an answer. The fact that it works for you doesn't help or solves OP's problem, therefore it is not exactly an answer – Tomerikoo Mar 02 '20 at 15:13