简体   繁体   中英

Is it possible to use a loop to assign multiple variables to different values in python

I have seen duplicates of this, but the original question was never answered: is it possible to assign values to multiple variables using a loop or some other method that would be more efficient that writing out all the variables in hard code.

NOTE: I do not want to use dictionaries or list, I want to use variables. My question is whether it is possible to assign multiple variables at once using a loop or other method, not using dictionaries.

If this is not possible just say so, but I really don't want to see another answer describing how to use lists or dictionaries.

Duplicates: Python: assigning multiple variables at once

Assign Many Variables at Once, Python


DISCLAIMER : The global()[] function that I talk about here may have more uses/parameters/arguments, but I am just telling you what I know. You can experiment with it on your own


Ok, now that I have found the answer, I'll post it here for future members to view. Note that, as mentioned above, this technique is seldom used, but it's great to know for those corner cases.

The crucial function here is the global()[] function in which you input a string and it turns it into a variable name. You leave the () completely empty, and enter the string into the [] . Now, this may seem useless, but one thing you can do is,

for i in range(100):
    global()["Var"+str(i)] = i

Now you have 100 variables of the form Var# where # is the number, and, in this case, the value of the variable. This is a very, very simple case, and because of this extra flexibility, there are several things you can do with this.

Again, you will probably use this very few times while programming in python, since using extra lists of strings and values and then using this to create variables is unnecessary and inefficient, but , in the right places, this can save you a lot of time. Just comment if you have any questions since I am not that good at explaining things.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM