How to Create a Dynamic Variable Name in Python

To create a dynamic variable in Python, use a dictionary. Set the key as the name of the variable and the value as the content of the variable. Dictionaries are mutable, which means we can edit the name and the content of the variable at any time.

 

name = 'number'
value = 10

variables = {name: value}

print(variables['number'])
10

 

Creating dynamic variables is particularly useful when using list comprehension. Here is an example of just such a scenario:

 

list_1 = [1,2,3]
list_2 = [4,5,6]
list_3 = [7,8,9]

items = {1: list_1, 2: list_2, 3: list_3}

lists = [items[i] for i in items]

print(lists)
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]