python dynamic variable name – How to create a dynamic variable name in Python?

python dynamic variable name also known as a Variable variable, Using globals() method, Using locals() method, Using exec() method and Using vars() method.

python dynamic variable name

Python program to create dynamically named variables from user input. The creation of a dynamic variable name in Python can be achieved with the help of iteration. This approach will also use the globals() function in addition to the for loop.

Method 1: Using globals() method.

Set_DDVar_Define = "pakainfo"

globals()[Set_DDVar_Define] = 2022

print(pakainfo)

Method 2: Using locals() method.


Set_DDVar_Define = "pakainfo"
locals()[Set_DDVar_Define] = 2022

print(pakainfo)

Method 3: Using exec() method.


Set_DDVar_Define = "pakainfo"

exec("%s = %d" % (Set_DDVar_Define, 2022))
print(pakainfo)

Method 4: Using vars() method


Set_DDVar_Define = "pakainfo"

vars()[Set_DDVar_Define] = 2022
print(pakainfo)

how to create dynamic variable names in python?

for i in range(0, 9):
    globals()[f"my_variable{i}"] = f"Welcome from variable number {i}!"


print(my_variable3)
# Welcome from variable number 3!

how to create dynamic variable names in python?

for x in range(0, 9):
    globals()['string%s' % x] = 'Welcome'
# string0 = 'Welcome', string1 = 'Welcome' ... string8 = 'Welcome'

USE A DICTIONARY TO CREATE A DYNAMIC VARIABLE NAME

name = "a"
value = True
player_message = {name: value}
print(player_message["a"])

Don’t Miss : How To Read And Write Files In Python 3?

I hope you get an idea about python dynamic variable name.
I would like to have feedback on my infinityknow.com blog.
Your valuable feedback, question, or comments about this article are always welcome.
If you enjoyed and liked this post, don’t forget to share.

Leave a Comment