I was just wondering if anyone knew of a way to change variable names based off of a for loop for something like this:
for i in range(3) group+i=self.getGroup(selected, header+i)
so that the names of the variables change to accomodate the data. Thanks!
~Sam
If you're using the Python Idle(GUI) you can Ctrl + H and select Replace All. Show activity on this post. Visual Studio Code is Ctrl + Shift + L and begin typing. Sublime/Atom are alt + F3.
Is it okay to create multiple for loops with the same variable name? Yes, it's OK and widespread practice to do so.
You probably want a dict instead of separate variables. For example
d = {} for i in range(3): d["group" + str(i)] = self.getGroup(selected, header+i)
If you insist on actually modifying local variables, you could use the locals
function:
for i in range(3): locals()["group"+str(i)] = self.getGroup(selected, header+i)
On the other hand, if what you actually want is to modify instance variables of the class you're in, then you can use the setattr
function
for i in group(3): setattr(self, "group"+str(i), self.getGroup(selected, header+i)
And of course, I'm assuming with all of these examples that you don't just want a list:
groups = [self.getGroup(i,header+i) for i in range(3)]
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