Skip to content
Advertisement

Assign a value to a list of variables using a loop

I can do this in C, but I haven’t come across it in Python.

Say I have a few variables:

variable1 = None
variable2 = None
variable3 = None
variable4 = None
variable5 = None

and I have list of values [1, 2, 3, 4]

how can I assign the values to the variables with a single loop so I get the following result:

variable1 = 1
variable2 = 2
variable3 = 3
variable4 = 4
variable5 = None

Advertisement

Answer

While you technically can modify local variables, doing so is very discouraged. Instead, you should store those values in a dictionary instead:

variables = {
    variable1: None,
    variable2: None,
    variable3: None,
    variable4: None,
    variable5: None
}

values = [1, 2, 3, 4]

for i, value in enumerate(values):
    variables['variable' + (i + 1)] = value

But of course, if all those variables differentiate is the number, you can simply use a list as well:

# This will create a list with 5 None values, i.e. variables[0] .. variables[4]
variables = [None] * 5

for i, value in enumerate(values):
    variables[i] = value
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement