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.
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.
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:Recommended reading
A variable doesn't exist until you create it. Simply referencing a variable isn't enough to create it. When you do
[one, two, three]
you are referencing the variablesone
,two
andthree
before they are created.No, it doesn't work like that.
You can try:
This work by defining the variables in a multiple assignment. Just as you can use
a, b = 1, 2
. This will unroll therange
and assign its values to the LHS variables, so it looks like your loop (except that it works).Another option (which I wouldn't recommend in a real program...) would be to introduce the variable names in an exec statement:
I think this approach is simpler.
Python variables are names for values. They don't really "contain" the values.
for var in var_list:
causes 'var' to become a name for each element of the list, in turn. Inside the loop,var = num
does not affect the list: instead, it causesvar
to cease to be a name for the list element, and instead start being a name for whatevernum
currently names.Similarly, when you create the list, if
one
,two
andthree
aren't already names for values, then you can't use them like that, because you are asking to create a list of the values that have those names (and then causevar_list
to be a name for that list). Note that the list doesn't really contain the values, either: it references, i.e. shares them.