Python Dynamic Variable Name

  1. Use the for Loop to Create a Dynamic Variable Name in Python
  2. Use a Dictionary to Create a Dynamic Variable Name in Python

A dynamic variable name, which can likewise be known as a variable variable, is fundamentally a variable with a name that is the estimation of another variable.

Although Python itself is a highly dynamic language, and almost everything in a Python code is an object, it is possible to create dynamic variables in Python.

This tutorial will discuss different methods to create a dynamic variable name in Python.

Use the for Loop to Create a Dynamic Variable Name in Python

The creation of a dynamic variable name in Python can be achieved with the help of iteration.

Along with the for loop, the globals() function will also be used in this method.

The globals() method in Python provides the output as a dictionary of the current global symbol table.

The following code uses the for loop and the globals() method to create a dynamic variable name in Python.

for n in range(0, 7):
    globals()['strg%s' % n] = 'Hello'
# strg0 = 'Hello', strg1 = 'Hello' ... strg6 = 'Hello'

for x in range(0, 7):
    globals()[f"variable1{x}"] = f"Hello the variable number {x}!"


print(variable15)

Output:

Hello from variable number 5!

Use a Dictionary to Create a Dynamic Variable Name in Python

A dictionary is one of the four built-in data-types provided by Python along with tuple, list, and set. It is used to store data in the form of key: value pairs. A dictionary is both ordered (in Python 3.7 and above) and mutable. It is written with curly brackets {}. In addition to this, dictionaries cannot have any duplicates.

A dictionary has both a key and value, so it is easy to create a dynamic variable name using dictionaries.

The following code uses a dictionary to create a dynamic variable name in python.

var = "a"
val = 4
dict1 = {var: val}
print(dict1["a"])

Output:

4

Although the creation of a dynamic variable name is possible in Python, It is needless and unnecessary as data in Python is created dynamically. Python references the objects in the code. If the reference of the object exists, then the object itself exists.

Creating a variable in this way is not recommended.

Contribute
DelftStack is a collective effort contributed by software geeks like you. If you like the article and would like to contribute to DelftStack by writing paid articles, you can check the write for us page.

Related Article - Python Variable

  • Global Variables in Python