-1

NOTE: Please read till the end, I don't want dictionaries. For example, I have the global variable called var1 and I have the following:

i = 0
for i in range(0, 20):
    var1 = i
    i += 1

I want to create a new variable called var2 and store the value from the second iteration into that, instead of the initial var1 and so on for every iteration.

I also don't want to store it in some list var and use var[i] for every iteration.

I want the variable names to logically be named for every iteration.

Is there a direct solution or is there any way I can make a variable with the contents of a string?

The main intent of the question is to know if I can generate a new variable for every iteration with naming that has some logic behind it, instead of using lists.

Also, I do not want to define dictionaries as dictionaries have definite sizes and cannot flexibly expand themselves.

sighclone
  • 102
  • 1
  • 10
  • "I do not want to define dictionaries as dictionaries have definite sizes and cannot flexibly expand themselves"—this is nonsense. "I also don't want to store it in some list `var` and use `var[i]` for every iteration"—why not? "I want the variable names to logically be named for every iteration"—this is a huge antipattern. I cannot think of a single good reason to ever do this. If you have one I'd love to hear what it is. But unless you can provide that, the answer is to use a data structure like a list or a dict, depending on your needs. – ChrisGPT was on strike Dec 06 '20 at 16:07
  • It can technically be done, but it's exceedingly awkward and can have major security implications (e.g. via Kuldeep's suggestion to use `exec()`, which should be carefully avoided). Lists are the right tool to use here. – ChrisGPT was on strike Dec 06 '20 at 16:12
  • See [the answers on this question](https://stackoverflow.com/q/1373164/354577) if you're curious, but I hope you decide to use a built-in data structure like a list. – ChrisGPT was on strike Dec 06 '20 at 16:14

1 Answers1

-2

You can use exec

The exec() method executes the dynamically created program, which is either a string or a code object.

for i in range(0, 20):
    exec("%s = %d" % (f"var{i+1}",i))
print(var1)
print(var2)
print(var3)
print(var4)
print(var18)
print(var19)
0
1
2
3
17
18
Kuldeep Singh Sidhu
  • 3,748
  • 2
  • 12
  • 22
  • Please don't ever recommend using `exec()` without a very strong warning. `exec()` is very rarely the right tool to use, and using it carelessly leads to major security problems. – ChrisGPT was on strike Dec 06 '20 at 16:08