I\'ve been wondering if there is a way to use an iterator as a variable name in a Python loop. For example, if I wanted to create objects v0
, v1
,
The builtin method globals() returns a dictionary representing the current global symbol table.
You can add a variable to globals
like this:
globals()["v" + str(i)] = i**2
FYI: This is the answer to your question but certainly not the recommended way to go. Directly manipulating globals
is hack-solution that can mostly be avoided be some cleaner alternative. (See other comments in this thread)