0

I would like to set the variable name in a for loop, like:

for i in range(5):
    namei = i # this is a variable name

It will give me:

name0 = 0
name1 = 1
name2 = 2
name3 = 3
name4 = 4

does anyone know how to do that?

Thank you!

Kan
  • 169
  • 2
  • 6
  • You can modify `locals()` and `globals()` in some cases. If the containing scope is a module, there are valid reasons to do so, though arguably `getattr/setattr` are preferred. If it's your class, feel free to hack it either way you like. If it's a function, the only way other than `locals()` is to go through `foo.func_code.co_nlocals/co_varnames/co_consts` but you'd need to crate a new function on the fly. **in short** if you are not sure, use a data structure instead: https://docs.python.org/2/tutorial/datastructures.html – Dima Tisnek Apr 07 '15 at 09:22

1 Answers1

-1

Instead of having 5 separate variables, you should use an array.

Eg.

name = [] #Create an empty array

for i in range(5):
    name.append(i) #Add each value to your array

This will leave you with

name[0] = 0
name[1] = 1
...
etc.
Loocid
  • 6,112
  • 1
  • 24
  • 42