-1

I'm trying to create a lot of variables inside a loop.

for i in range(10):
    globals()[f"variables{i}"] = i

perfect, so now I have variables0 = 0, variables1 = 1, variables2 = 2, etc. But now, i want to access each one of them with a loop and I don't really know how to do that.

I know it's not gonna work, but anyways I've tried:

for i in range(10):
    print(variables{i})

Anyone know how can I point the right variable name inside a loop?

alex
  • 10,900
  • 15
  • 70
  • 100
  • 1
    You can access them in the same way you created them, via `globals()['var_name']`. A list or dict would probably be more appropriate here though – Iain Shelvington Apr 11 '22 at 09:59

2 Answers2

-1

You can use gloabals to dynamically acces to the values. No need of evaluate strings. You need to filter the dictionary by name, for example with a .startswith('variables')) and iterate over the list of key-value pairs representing the dictionary. I save the values in a list but it depends on your needs (you can just make a print).

# add variables danamically to global name
for i in range(10):
    globals()[f"variables{i}"] = i

# access to variables (and for ex store them in a list...)
d_vars = []
glbs = list((name, value) for name, value in globals().items() if name.startswith('variables'))

for i, (k, v) in enumerate(glbs):
    if k == (name:=f'variables{i}'):
        d_vars.append(v)
        # print(f'{name} = {v}')
    
print(d_vars)
cards
  • 3,936
  • 1
  • 7
  • 25
-2

You can use dictionary in this case

dict = {}
for i in range(0,10):
    dict[f'variable{i}'] = i

Or to answer your above question, you can use eval:

for i in range(10):
    print(eval(f'variables{i}'))

Mostly dictionary method is preferable.

Vaibhav Jadhav
  • 2,020
  • 1
  • 7
  • 20