Dynamic variable names in Python are very useful especially when you want variables that can change their names on the fly. This can be particularly useful when dealing with dynamic data or when working with user input.
Still, it’s generally best to avoid changing variable names dynamically unless absolutely necessary. Before we dig into dynamically coding variable names, there are other better practices such as Python dictionaries, which you may find more suitable and easier to use. However, if you’re sure that you need this feature, this is how you can do it:
Step 1: Using a Dictionary
A dictionary is a built-in Python data type that can store any number of Python objects, including other dictionary objects. Essentially, a dictionary is an associative array, where each key stores a specific value.
Keys can be of any immutable type and are typically strings or numbers. Here is how you can emulate a dynamically changing variable name with a dictionary:
1 2 3 4 5 6 |
# Create an emptydictionary var_dict = {} # Assign a value to aname in the dictionary var_dict['var1'] = 42 # Display the value of 'var1' print(var_dict['var1']) |
You can also use a loop to create variables in a dictionary:
1 2 3 4 |
for i in range(5): var_dict['var'+str(i)] = i*2 # Display the entire dictionary print(var_dict) |
Output:
var1: 42 var0: 0 var1: 2 var2: 4 var3: 6 var4: 8
Step 2: Using the exec() Function
Another approach is to use the exec() function which parses a string of Python code and executes it. Keep in mind though, using exec() could be a security risk if you are dealing with user input or data from untrusted sources.
1 2 3 4 5 |
for i in range(5): exec('var' + str(i) + '= i*2') # Display the created variables for i in range(5): exec('print(var' +str(i)+ ')') |
Output:
0 2 4 6 8
The Full Python Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
# Using a dictionary var_dict = {} var_dict['var1'] = 42 print(var_dict['var1']) for i in range(5): var_dict['var'+str(i)] = i*2 print(var_dict) #Using exec() function for i in range(5): exec('var' + str(i) + '= i*2') for i in range(5): exec('print(var' + str(i)+ ')') |
In Conclusion
While dynamically changing variable names in Python can be done, it’s usually a practice that’s best to avoid. It may introduce complexity and potential bugs to your code. Typically, utilizing Python’s robust capabilities with lists, dictionaries, objects, or another built-in data structure is a smarter choice.