'How to add variables with changing names through for loop in python?

Consider two or more variables whose names changes with every iteration of for loop. Now all these lists are to be summed i.e., key = [33, 55, 67]


a_1 = int\[21,41,51\]

a_2 = int\[1, 2, 3\]


a_3 = int\[11,12,13\]


key=\[\]


for i in \[1, 2, 3\]:


   for j in range(a_1):


      key+= \[a\_{}.\*j ,format(i)\]


print(key)

How can for loop change names of these variables, i.e., a_1, a_2 and a_3 with each iteration, while summing the corresponding entries of these variables?

I am expecting the result to be:

key =\[33, 55, 67\]


Solution 1:[1]

I hope this is not what you really wanted , doing a code generation on the fly which is possible by doing AST parsing and or using reflection utils.

Whenever you are in situations like these where you require variable names to be generated in a sequence and all those variables are containing homogeneous data, probably you should be looking at making those variables indices of array. In your example here, probably what you want to do is have an array of arrays.

So

a[][]= new int[3][3]

so your variables become a[0], a[1],a[2]

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 TruckDriver