-2
a1 = 0
a2 = 1

x = [] #here I have declared an empty list
for i in range(2):
    x.append('a'+str(i+1)) #to append the variable with a numbering scheme
print (x)

This is a sample python code. A similar situation that I am facing in a programming task .

Here the output is ['a1','a2'] instead I need the output as [0,1]. Can someone help me with this ?

yatu
  • 86,083
  • 12
  • 84
  • 139
Aadithya Sathya
  • 797
  • 1
  • 6
  • 12

3 Answers3

2

Use a dictionary for this:

d = {'a1': 0, 'a2':1}
x = [] #here I have declared an empty list
for i in range(2):
    x.append(d['a'+str(i+1)]) #to append the variable with a numbering scheme
print (x)

DSC
  • 1,153
  • 7
  • 21
1

If you MUST use variables already existing in your scope, you can use locals() to get all local variables as a dict

a1 = 0
a2 = 1

x = [] #here I have declared an empty list
for i in range(2):
    x.append(locals()['a'+str(i+1)]) #to append the variable with a numbering scheme
print (x)
Adam.Er8
  • 12,675
  • 3
  • 26
  • 38
  • Good for indicating that this should be avoided at all costs – DSC Jun 11 '19 at 14:03
  • 2
    Even then it would probably be better (less bad?) to use `locals` or `globals` instead of `eval`. (Oh, you just did while I typed this...) – tobias_k Jun 11 '19 at 14:04
  • Hi , Thankyou so much for the help . I dont have much experience in programming. Also the solution that you gave me works like I expected. I would like to know what consequences will I have in this kind of programming since you have mentioned "very bad programming practice" – Aadithya Sathya Jun 11 '19 at 14:09
  • 1
    eval/exec are generally abused to do a task where they aren't needed, very slow, opens up security issues,.... – DSC Jun 11 '19 at 14:12
  • @AadithyaSathya my first version was using `eval`, which is not recommended because it executes code (it interprents the parameter as python code), which can lead to severe security issues and bugs. – Adam.Er8 Jun 11 '19 at 14:13
0
vars = {
    'a1': 0,
    'a2': 1,
}

x = []

for var in vars.keys():
    x.append(vars[var])

print(x)
Gokhan Gerdan
  • 1,222
  • 6
  • 19