How to Dynamically Change Variable Names in Python

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:

You can also use a loop to create variables in a dictionary:

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.

Output:

0
2
4
6
8

The Full Python Code:

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.