Hello guys. How are you all? I hope you all fine. In this tutorial we will learn about How to get python dynamic variable name. so without wasting time lets learn about of this.
How to get python dynamic variable name
python dynamic variable name
to get python dynamic variable name just Use globals().By using globals() you can get the dynamic variable. Lets learn about of this by given below example:
myvar = "year" globals()[myvar] = 2022 print(year)
Output :2022
How to get python dynamic variable name
to get python dynamic variable name just Use locals().By using locals() you can get the dynamic variable. Lets learn about of this by given below example:
myvar = "year" locals()[myvar] = 2022 print(year)
Output :2022
Method 1: Use globals()
By using globals() you can get the dynamic variable. Lets learn about of this by given below example:
myvar = "year"
globals()[myvar] = 2022
print(year)
Output :
2022
Method 2: Use locals()
By using locals() you can get the dynamic variable. Lets learn about of this by given below example:
myvar = "year"
locals()[myvar] = 2022
print(year)
Output :
2022
Method 3: Use vars()
By using vars() you can get the dynamic variable. Lets learn about of this by given below example:
myvar = "year"
vars()[myvar] = 2022
print(year)
Output :
2022
Method 4: Use exec()
By using exec() you can get the dynamic variable. Lets learn about of this by given below example:
myvar = "year"
exec("%s = %d" % (myvar, 2022))
print(year)
Output :
2022
Conclusion
It’s all About this Tutorial. Hope all methods helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which method worked for you?
Also, Read