Johnn Kaita
Johnn Kaita

Reputation: 452

Dynamically declare and assign variables in a loop

How can achieve the following: I want to create unique dynamic variables in a for loop self."INSERT DYNAMIC VARIABLE HERE"

list = [box1, box2, box3]
for value in list:
 self."" = Button()

Upvotes: 0

Views: 844

Answers (1)

U13-Forward
U13-Forward

Reputation: 71570

You could use exec, but it's highly not recommended see here:

l = [box1, box2, box3]
for value in l:
    exec(f"self.{value} = Button()")

I would recommend you to just store it in a dictionary:

l = [box1, box2, box3]
self.variables = {}
for value in l:
    self.variables[value] = Button()

Upvotes: 1

Related Questions