'Dynamic variable names (at runtime) in Python

I predefine some variables and want call them in a for loop:

a1 = 10
a2 = 20 
for i in range(1, 3):
  value=("a%s" %i)
  print(value)

And I get a1,a2, but I want to have 10,20. How can I solve the problem?



Solution 1:[1]

Accessing globals() should do the trick, but there are better ways to do this (see comments on your original post)

a1=10
a2=20 
for i in range(1,3):
  value=("a%s" %i)
  print(globals()[value])

Solution 2:[2]

If you mean you want to loop through a1 and a2, you want to put them in a collection and loop through that:

a1=10
a2=20
combined = a1, a2
for i in combined:
  print(i)

Output

10
20

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 iScripters
Solution 2 Peter Mortensen