How to create dynamic variable name in Python

A dynamic variable name, sometimes called a variable, is a variable with a name that is the estimation of another variable.
Despite the fact that Python is a very dynamic language in which nearly everything is an object, it is possible to construct dynamic variables in Python.

In Python, how do you make a dynamic variable name?

This lesson will go through many techniques for naming a dynamic variable in Python.

There are many ways of it, Let’s see the first step

1. Create a Dynamic Variable Name in Python Using for Loop

Iteration may be used to create a dynamic variable name in Python.

This approach will also use the globals() function in addition to the for loop.

Python’s globals() function returns a dictionary containing the current global symbol table.

In Python, the for loop and the globals() function are used to construct a dynamic variable name.

Let’s learn through an Example,

for x in range(0, 7):
    globals()[f"variable1{x}"] = f"Hello CodeSpeedy Student {x}!!!"
print(variable12)

Output:

Hello CodeSpeedy Student 2!!!

2. Create a Dynamic Variable Name in Python Using a Dictionary

Dictionaries have both a key and a value, it’s simple to construct a dynamic variable name using them.

In Python, the following code creates a dynamic variable name using a dictionary.

var = "CodeSpeedy"
val = 1
dict1 = {var: val}
print(dict1["CodeSpeedy"])

Output:

1

However, it is possible to define a dynamic variable name in Python, it is pointless and unneeded because Python data is produced dynamically. The objects in Python are referred to throughout the code. If the item’s reference exists, the object itself exists.

Leave a Reply

Your email address will not be published.