0

Let's say I have a lot of variables like so myvar_{number} e.g. myvar_1, myvar_2, myvar_3, ...myvar_1000.

Skeleton code:

Full piece of code:

# supposing that instead of 1000 global variables there are only two of them:
myvar_1=None
# do some other stuff with myvar_1
#[...]
myvar_8=None
# do some other stuff with myvar_8
#[...]

my_new_lst = [1, 8] # supposed list with 1000 variables but for the sake of example just two of them

# Here I want to set each variable to its index number multiplied by 2, e.g. myvar_1 = 2 * 1 = 2; myvar_8 = 2 * 8 = 16; and finally print them.

# so, I tried this:
for each in my_new_lst:
    print(f'{global myvar_{each}=2*each}') # I know it just print it but how to set it?

# finally print them:
print(myvar_1)
print(myvar_8)

The error it gives to me is:

 File "<fstring>", line 1
    (avg_interval_{each}=2*each)
                  ^
SyntaxError: invalid syntax

P.S. I've found How to get the variable names from the string for the format() method which is asking about something somehow similar but it doesn't help.

martineau
  • 119,623
  • 25
  • 170
  • 301
YoYoYo
  • 439
  • 2
  • 11

0 Answers0