Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing variable names with Python for loops [duplicate]

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

like image 205
user130633 Avatar asked Jun 29 '09 19:06

user130633


People also ask

How do you change multiple variable names in Python?

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.

Can two for loops have the same variable?

Is it okay to create multiple for loops with the same variable name? Yes, it's OK and widespread practice to do so.


1 Answers

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)] 
like image 172
Eli Courtwright Avatar answered Oct 12 '22 04:10

Eli Courtwright