0

I know its possible to declare dynamic variables using this method :

for x in range(0, 7):
    globals()[f"variable1{x}"] = x

What i want to do is something like :

ls = [1,31,42,56, ...]
for x in range(0, len(ls)):
    globals()[f"variable{x}"] = 10*x if ls[x] %2 == 0 else globals()[f"variable{x}"] = 11*x

Code is random beacause i tried to make it as simple as possible, apologies.

What i am actually trying to do is :

for i in range(0,4):
       globals()[f"numb{i}"] = tk.Label(root, text=(best[i] +"\n"+dates[0]),width=10,height=3, bg="#F4F5B7") if len(best) >= i else tk.Label(root, text=('UNDEFINED'),width=10,height=3, bg="#F4F5B7")
numb[i].grid(row=1,column=(i+5))

Where best[] is user inputed

flair
  • 21
  • 3
  • The syntax would be globals()[f"variable{x}"] = 10*x if ls[x] %2 == 0 else 11*x You do not need to repeat the "globals()[f"variable{x}"] = " in a if else expression. – charon25 Nov 24 '22 at 14:53

1 Answers1

1

You try to assign the value in the if and the else. The "x if condition else y" is by itself a value so you can assign it to something you don't have to assign in the if and else part. So you should use :

ls = [1,31,42,56, ...]
for x in range(0, len(ls)):
    globals()[f"variable{x}"] = 10*x if ls[x] % 2 == 0 else 11*x

Please also note that in 9 out of 10 cases, dynamic variable allocation is a bad practice, in most situation it can be replaced with a dictionary like :

ls = [1,31,42,56, ...]
values = {}
for x in range(0, len(ls)):
    values[f"variable{x}"] = 10*x if ls[x] % 2 == 0 else 11*x

#Then later access the values this way
print(values["variable31"]) #print whatever is 11**31
Xiidref
  • 1,456
  • 8
  • 20
  • i know but the thing is that i am trying to set tkinter labels, wich i guess are not 'values' per say – flair Nov 24 '22 at 15:06
  • No they are values it is perfectly fine to do `values["numb2"] = tk.Label(root, text=(best[2] +"\n"+dates[0]),width=10,height=3, bg="#F4F5B7") if len(best) >= 2 else tk.Label(root, text=('UNDEFINED'),width=10,height=3, bg="#F4F5B7") ` then later to use `values["numb2"].grid(row=1,column=(i+5))` – Xiidref Nov 24 '22 at 15:16