var_list = [one, two, three]
num = 1
for var in var_list:
var = num
num += 1
The above gives me an error that 'one' doesn't exist. Can you not assign in this way? I want to assign an incrementing number for each var in the list. So I want the equivalent of
one = 1
two = 2
three = 3
but without having to manually create and initialize all variables. How can I do this?
First of all, you cannot reassign a loop variable—well, you can, but that won't change the list you are iterating over. So setting foo = 0 will not change the list, but only the local variable foo (which happens to contain the value for the iteration at the begin of each iteration).
Often the variable that controls a for loop is needed only for the purposes of the loop and is not used elsewhere. When this is the case, it is possible to declare the variable inside the initialization portion of the for.
You can assign the same value to multiple variables by using = consecutively. This is useful, for example, when initializing multiple variables to the same value. It is also possible to assign another value into one after assigning the same value.
You can access the dictionary of global variables with the globals()
built-in function. The dictionary uses strings for keys, which means, you can create variables with names given as strings at run-time, like this:
>>> var_names = ["one", "two", "three"]
>>> count = 1
>>> for name in var_names:
... globals()[name] = count
... count += 1
...
>>> one
1
>>> two
2
>>> three
3
>>> globals()[raw_input()] = 42
answer
>>> answer
42
Recommended reading
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With