0

Consider the following:

var1 = 0
var2 = 1
var3 = 2
var4 = 3

If I were to add another variable, I could manually add it:

var1 = 0
...
var5 = 4

Note that the values assigned to the variables are numbers increasing, in this case, by one. I would like to change by how much too, say by three:

var1 = 0
var2 = 3
var3 = 6
var4 = 9
var5 = 12

The closest thing I could find in this regards was the following, which is found in this answer:

for j in range(1,10,1):
    exec('var_%d = j'%j)
  • range() allows me to set the starting and ending point of the values by a given step.
  • exec() allows me to execute the statement.

The author of the answer warns against the usage of this, but I fail to see why. I suppose this is because of exec(). However, I don't see another way around this, so I asked this question.

Nameless
  • 383
  • 2
  • 11
  • 6
    use a dictionary – Marat Jan 17 '22 at 04:41
  • 5
    Use a *list*: `vars = list(range(0, 15,3))` then `vars[0]`, `vars[1]`, etc to access. Can an *almost* always be sure if your solution involves `exec()` it is wrong. See also: https://stackoverflow.com/questions/1373164/how-do-i-create-variable-variables – Mark Jan 17 '22 at 04:43
  • I don't need a list but *exactly* multiple variables, as exemplified above. – Nameless Jan 17 '22 at 04:53
  • @Nameless Why do you think you need multiple variables? I can almost guarantee that you don't. You can [edit] to clarify if needed. I closed your question under one where most answers recommend a list, but by all means LMK if you disagree. – wjandrea Jan 17 '22 at 05:03
  • @wjandrea, Nameless doesn't need list, He just need to define variable at runtime... Please check if my solution provide any help – Shivam Seth Jan 17 '22 at 05:06
  • 1
    @Shivam Defining variables at runtime [is not great practice](/a/1834754/4518341). A list is a better option, as explained in [this answer](/a/38972761/4518341). – wjandrea Jan 17 '22 at 05:12
  • @wjandrea, I agree with you about coding practices, But nothing stops us to learn different ways to implement ( good or workaround ), With more and more practices we learn more and grow – Shivam Seth Jan 17 '22 at 05:16

1 Answers1

0

Use globals() :: The globals() method returns the dictionary of the current global symbol table.

To define variable dynamically:

globals()['a'] = 10
print(a)

Output will be 10

To Define variables as requests:

for i in range(1,10,1):
    x = 'var%d'%i
    globals()[x] = i * 3

print(var1)
print(var7)
print(var9)

Output

0
21
27
Shivam Seth
  • 677
  • 1
  • 8
  • 21
  • Yes, thank you for your quick answer. This is exactly what I was looking for. – Nameless Jan 17 '22 at 05:07
  • 1
    Apart from it being improper coding, this will always create the variable globally. Any variables you try to declare in scope will not work (apart from global scope). – TwoFace Jan 17 '22 at 05:41