I want to create a dynamic variable and use it [closed]

I am trying to create and use a dynamic variable in Python for the first time.

for i in range(0,len(test_data)):
     globals()["test_list_{}".format(test_data[i])]=[]
     globals()["test_calculation_{}".format(test_data[i])]=0

First, I created test_list_number and test_calculation_number as global variables.

Then I want to use this in for and use it for calculations. The code I wrote here was made by simplifying the code I’m going to use.

How do I change the numbers in the two for statements below?

enter image description here

1

————–Below is a code example. ————-

import pandas as pd
import numpy as np

X=list(np.random.random(100)*100)
Y=list(np.random.random(100)*100)

test_data= [2,5,7,8]

test_dict={(i,j):np.hypot(X[i]-X[j],Y[i]-Y[j]) for i in range(0,100) for j in range(0,100)}



test_df_data2={
    'index' : [1,2,3],
    'data1' : [3,5,6],
    'data2' : [2,5,6]
}



test_df_data5={
    'index' : [1,2,3],
    'data1' : [8,3,1],
    'data2' : [3,2,7]
}

test_df_2  =pd.DataFrame(test_df_data2)
test_df_5  =pd.DataFrame(test_df_data5)


for i in range(0,len(test_data)):
    globals()["test_list_{}".format(test_data[i])]=[]
    globals()["test_calculation_{}".format(test_data[i])]=0

    
    
for i in range(0, len(test_df_2     )  ):
    test_list_2       .append((test_df_2   .data1[i],test_df_2     .data2      [i]))

for i in range(len(test_list_2    )):
    test_calculation_2    = test_calculation_2     + test_dict[test_list_2       [i] ]

    
print( test_calculation_2)



Answer

Short answer, do not do this!

It is widely accepted to be a bad practice (see for example). You have a high risk of doing something difficult to debug, to overwrite existing variables, or to use the wrong namespace. In addition there are eventual pitfalls and lack of robust methods to do this.

Use a container instead. You will have a shorter, cleaner, and easier to debug code.

Dictionaries are ideal for this:

# initialize
my_dfs = {}

# computation
for i in …:
    my_dfs[f'df_computation_{i}'] = …

# access
my_dfs['df_computation_42']