. Advertisement .
..3..
. Advertisement .
..4..
Python is one of the most popular programming languages in the world today. In fact, it’s one of the most used programming languages across the globe. However, if you need to get the dynamic variable name in Python, then this blog will show you how to do that. Read on.
How Can You Get The Dynamic Variable Name in Python?
Utilize globals() to receive the name of a Python dynamic variable. In Python, you can receive the dynamic variable by utilizing globals(). Let’s take a look at an example of this:
yvar = “year” globals()[myvar] = 2022 print(year)
Result:
2022
Option 1: Utilize globals()
In Python, you can receive the dynamic variable by utilizing globals(). Let’s take a look at an example of this:
yvar = “year” globals()[myvar] = 2022 print(year)
Result:
2022
Option 2: Utilize locals()
You can also receive the dynamic variable by utilizing locals(). Let’s take a look at an example of this:
myvar = "year" locals()[myvar] = 2022 print(year)
Result:
2022
Option 3: Utilize vars()
You can also receive the dynamic variable by utilizing vars(). Let’s take a look at an example of this:
myvar = "year" vars()[myvar] = 2022 print(year)
Result:
2022
Option 4: Utilize exec()
You can also receive the dynamic variable by utilizing exec(). Let’s take a look at an example of this:
myvar = "year" exec("%s = %d" % (myvar, 2022)) print(year)
Result:
2022
Conclusion
We hope you enjoyed our blog about getting the dynamic variable name in Python. If you have any other questions or concerns about this issue, please leave a comment below. Thank you for reading; we are always excited when one of our posts can provide useful information on a topic like this!
Leave a comment