1

I want to define a number of variables that depends on a certain k. the var name depends on the number of the iteration for example:

for i in range(1,k):
    th(i) = i

result should be: th1=1, th2=2, th3=3...

I tried:

for i in range(1,k):
    th+str(i) = i

didn't work.

any suggestion?

Anshul Goyal
  • 73,278
  • 37
  • 149
  • 186
Rtucan
  • 157
  • 1
  • 11
  • possible duplicate of [Changing variable names with Python for loops](http://stackoverflow.com/questions/1060090/changing-variable-names-with-python-for-loops) – Mathias711 Jun 09 '15 at 09:42

2 Answers2

2

The usual thing to do in such cases is to use a dict, and save the variables as keys in it. Example:

variables = {"th%s" % i: i for i in range(1, 100)}

This gives output of the form below, and the variables can be accessed via the keys:

>>> variables
{'th99': 99, 'th98': 98, ...}
>>> variables["th1"]
1
>>> variables["th10"]
10
Anshul Goyal
  • 73,278
  • 37
  • 149
  • 186
1

You'd better to use a list instead of multiple variables to store a sequence of values.

data = []
for i in range(1, k):
    data.append(i)

You can access the items later using indexing:

data[index]
falsetru
  • 357,413
  • 63
  • 732
  • 636