1

I am trying to create loop in Python to call different variables.

example0="result1"
example1="result2"
example2="result3"
example3="result4"
example4="result5"


for i in range(5):
    print(example+(i))

The result I expect will be

result1
result2
result3
result4
result5

I have tried several solutions, the furthest I got is with :

for i in range(5):
    locals()["example"+str(i)]()

but I recieve error

"    locals()["example"+str(i)]()
TypeError: 'str' object is not callable
Matus Hmelar
  • 348
  • 3
  • 13
  • 1
    Possible duplicate of [How do I create a variable number of variables?](https://stackoverflow.com/questions/1373164/how-do-i-create-a-variable-number-of-variables) – Olvin Roght May 24 '19 at 11:57
  • Also you can check [this](https://stackoverflow.com/a/55949845/10824407) and [this](https://stackoverflow.com/a/55933230/10824407) answers where I've already explain how you can do this and why you should avoid this. – Olvin Roght May 24 '19 at 11:59
  • 1
    Unless you have a very specific usage case where you need to access `locals()` directly and cannot create a list or a dictionary instead, it would be advisable to use a list or a dict. It does not seem like you have such a usage case. This is what containers are for. – user10186512 May 24 '19 at 12:02

3 Answers3

1

I guess this would be a way to go:

example0="result1"
example1="result2"
example2="result3"
example3="result4"
example4="result5"


for i in range(5):
    print(locals()["example"+str(i)])

Output:

result1
result2
result3
result4
result5
Toni Sredanović
  • 2,280
  • 1
  • 11
  • 13
0

With the last parentheses you are considering that the variable called result followed by the number you touch is a function. And he must call her. Remove those parentheses. For example:

for i in range(5):
  print locals()["example"+str(i)]
-1

try using "str". It may work :) .