Rtucan
Rtucan

Reputation: 157

Define variables in loop where var name depends on iteration

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?

Upvotes: 1

Views: 667

Answers (2)

falsetru
falsetru

Reputation: 368954

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]

Upvotes: 1

Anshul Goyal
Anshul Goyal

Reputation: 76857

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

Upvotes: 2

Related Questions