Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assigning values to variables in a list using a loop

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?

like image 309
johnharris85 Avatar asked Jan 14 '11 02:01

johnharris85


People also ask

How do you assign a value to a list in a loop in Python?

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).

Can you assign a variable to a for loop?

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.

How do you assign multiple values to a variable in Python?

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.


1 Answers

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

like image 66
Michael Cornelius Avatar answered Oct 13 '22 14:10

Michael Cornelius