Change variable name in loop python

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!



376k78 gold badges503 silver badges771 bronze badges

asked Jun 29, 2009 at 19:38


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

answered Jun 29, 2009 at 19:43

Eli CourtwrightEli Courtwright

179k65 gold badges208 silver badges256 bronze badges


Use a list.

groups = [0]*3
for i in xrange(3):
    groups[i] = self.getGroup(selected, header + i)

or more "Pythonically":

groups = [self.getGroup(selected, header + i) for i in xrange(3)]

For what it's worth, you could try to create variables the "wrong" way, i.e. by modifying the dictionary which holds their values:

l = locals()
for i in xrange(3):
    l['group' + str(i)] = self.getGroup(selected, header + i)

but that's really bad form, and possibly not even guaranteed to work.

answered Jun 29, 2009 at 19:45

Change variable name in loop python

David ZDavid Z

124k26 gold badges249 silver badges275 bronze badges

Definitely should use a dict using the "group" + str(i) key as described in the accepted solution but I wanted to share a solution using exec. Its a way to parse strings into commands & execute them dynamically. It would allow to create these scalar variable names as per your requirement instead of using a dict. This might help in regards what not to do, and just because you can doesn't mean you should. Its a good solution only if using scalar variables is a hard requirement:

l = locals()
for i in xrange(3):
    exec("group" + str(i) + "= self.getGroup(selected, header + i)")

Another example where this could work using a Django model example. The exec alternative solution is commented out and the better way of handling such a case using the dict attribute makes more sense:

Class A(models.Model):


    def __getitem__(self, item):  # a.__getitem__('id')
        #exec("attrb = self." + item)
        #return attrb
        return self.__dict__[item]

It might make more sense to extend from a dictionary in the first place to get setattr and getattr functions.

A situation which involves parsing, for example generating & executing python commands dynamically, exec is what you want :) More on exec here.

answered May 29, 2014 at 15:52


32.1k10 gold badges138 silver badges108 bronze badges

It looks like you want to use a list instead:

for i in range(3):
     group[i]=self.getGroup(selected, header+i)

Mark Roddy

26.1k19 gold badges66 silver badges71 bronze badges

answered Jun 29, 2009 at 19:43

Greg HewgillGreg Hewgill

908k177 gold badges1131 silver badges1267 bronze badges


You could access your class's __dict__ attribute:

for i in range(3)
     self.__dict__['group%d' % i]=self.getGroup(selected, header+i)

But why can't you just use an array named group?

answered Jun 29, 2009 at 19:44


38.2k12 gold badges93 silver badges91 bronze badges


How do you change a variable name in a loop?

You can't change the name of a variable. What you probably want to do is create new values with new names each time through the loop..
variable = 0..
mylist = [0, 1, 2, 3].
for x in mylist:.
variable = x..

How do you dynamically change a variable name in Python?

Use the for Loop to Create a Dynamic Variable Name in Python The globals() method in Python provides the output as a dictionary of the current global symbol table. The following code uses the for loop and the globals() method to create a dynamic variable name in Python. Output: Copy Hello from variable number 5!

How do you change a variable name in Python?

In the editor, select an element you want to rename. If you need to rename a file, select one in the Project tool window. Press Shift+F6 or from the main menu, select Refactor | Rename.

How do you change a variable value in Python?

Mutable and immutable types Some values in python can be modified, and some cannot. This does not ever mean that we can't change the value of a variable – but if a variable contains a value of an immutable type, we can only assign it a new value. We cannot alter the existing value in any way.