2

I want to print out variables named a1, a2, a3, ... etc. using for loop in python.

Is there a way to implement this? For example,

a0 = 3
a1 = 4
a2 = 5
for i in range(3):
    tmps = 'a' + '%d' %i
    print(tmps)

This will only print out

a0
a1
a2

I want my code to print out 3 4 5

C. Harry
  • 63
  • 7

2 Answers2

4

You should not assemble variable names this way, but you can place your variables in a collection (list), and print them:

a0 = 3
a1 = 4
a2 = 5

a = [a0, a1, a2]

for values in a:   # this iterates over the values in a

    print(values)
cbcoutinho
  • 634
  • 1
  • 12
  • 28
Reblochon Masque
  • 35,405
  • 10
  • 55
  • 80
  • 1
    In other programming languages it seems to be common practice to assemble variable names. I personally think that this solution is clearer, though. In most cases it's even better to not create all the variables in the first place, but store them in lists right away. – offeltoffel May 25 '18 at 12:50
  • i think, the questions intent was to check the feasability of dymamically printing the variables without making an explicit list of variables. – rawwar May 25 '18 at 13:02
  • Maybe, however, the OP could also be (and likely is) a beginner in need of understanding how to store and retrieve multiple variables. The question linked when this one was marked as duplicate answers your concern in great details. – Reblochon Masque May 25 '18 at 13:04
  • yeah, totally agree with you – rawwar May 25 '18 at 13:05
  • @Kalyan That was my question, yes. I wanted to ask if it is possible to print out variables 'without' making the list of variables. – C. Harry May 25 '18 at 13:07
  • @C.Harry, check my answer, i think that is what you wanted – rawwar May 25 '18 at 13:08
  • This answer should be deleted i guess. its not what user wants – Max May 27 '18 at 09:05
0

If you don't want to manually make a list of all the variable's and if the variable names are consistent you can use the following two ways

Method 1:

for each in locals():
    if each[0] =="a" and each[1:].isalnum():
        print(locals()[each])

Method 2: if you want to make it a for loop as you showed in the code template you can do the following

a0 = 3
a1 = 4
a2 = 5
for i in range(3):
    tmps = 'a' + '%d' %i
    print(eval(tmps))

what eval does is it evaluates a string and returns the value of it. To know more about eval, check out this Link

rawwar
  • 4,834
  • 9
  • 32
  • 57