I’m looking for a way, in python 3.2, to create a large number of variables and assign them values. Something like
X = 10
Y = 10
A = 0
B = 0
while X >= 0:
while Y >= 0:
cell[C]X[A] = A
cell[C]Y[B] = B
B = B + 1
Y = Y - 1
C = C + 1
A = A + 1
X = X - 1
Which would optimally create 200 variables of cell1X1, cell1Y1, cell2X1, cell2Y2, etc etc etc.
Is this possible? How would it be done?
Please keep in mind that I’m still very new to python, so please make things as simple as possible.
Also, while I understand that there are other ways to do this, and they they are probably better, I still want to know how to do things this way.
I understand dictionaries might be better in every possible way, but that’s not what I’m asking for.
Thanks for the help.
Edit: When I say new to python, I meant to say new to programming in general. Like very new. Like, just recently learned how to write functions.
It’s dark and hacky, but you could try:
But please don’t do this. It’s usually terrible practice.
As @delnan points out, it probably won’t work on some python versions and implementations.
locals()is the local namespace, which is part of Python’s implementation. You don’t really want to play with it.Another more important reason why you don’t want to do this – it’s a security and reliability nightmare. You can’t see what all the variable names will be, so it’s possible you will accidentally overwrite one of your other variables. You are getting all these “variables” from the same place, so it’s logical to put them all together in a dictionary.
I’ll explain why it works, at least in some cases: the local namespace is often implemented as a dictionary, and
locals()will sometimes return the local namespace dictionary, not a copy.Did that make no sense at all?
Python variables are like items in a dictionary. There’s one namespace for the module, one for the function, one “global” namespace, and so on.
locals()gets you the most local namespace, andglobals()gets you the global namespace.If the local namespace is actually implemented as a dictionary, you may be able edit it by editing
locals()(reaching into the guts of the python interpreter). HOWEVER, sometimes the local namespace is not implemented as a dictionary (for performance reasons) – this happens inside functions. In that case,locals()will give you a copy of the namespace, and you will not be able to edit it (or at least, it won’t change the local namespace).Still confused? Don’t do it.