How to dynamically create variables in a loop in Python

Published on Aug. 22, 2023, 12:15 p.m.

To dynamically create variables in a loop in Python, you can use a dictionary (or another data structure) to store and access the values. For example:

values = [1, 2, 3, 4, 5]
my_dict = {}
for i in range(len(values)):
    my_dict[f"var_{i}"] = values[i]

# Access the values using the dictionary key
print(my_dict["var_0"]) # Output: 1
print(my_dict["var_1"]) # Output: 2

In this example, instead of trying to access non-existent dynamically created variable names, we use the dictionary key (“var_0”, “var_1”, etc.) to access the values in the dictionary.

Tags:

related content