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:

JavaScript

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:

JavaScript

Advertisement

Answer

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

JavaScript

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

JavaScript
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement