41

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

S.Lott
  • 384,516
  • 81
  • 508
  • 779
user130633
  • 2,253
  • 4
  • 18
  • 11

5 Answers5

70

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)]
Eli Courtwright
  • 186,300
  • 67
  • 213
  • 256
  • what if the range is unknown, how can I approach this problem? –  Jan 08 '21 at 10:24
  • @EmmanuelManoloSiame you can use the `len()` method in Python. Read more about the len() method [here](https://www.programiz.com/python-programming/methods/built-in/len). – DC007744 Mar 07 '21 at 05:54
11

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.

David Z
  • 128,184
  • 27
  • 255
  • 279
6

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.

radtek
  • 34,210
  • 11
  • 144
  • 111
3

It looks like you want to use a list instead:

group=[]
for i in range(3):
     group[i]=self.getGroup(selected, header+i)
Mark Roddy
  • 27,122
  • 19
  • 67
  • 71
Greg Hewgill
  • 951,095
  • 183
  • 1,149
  • 1,285
  • 3
    Do you mean "Dictionary" or "List"? What's an Array? – S.Lott Jun 29 '09 at 19:46
  • 1
    I mean List, thanks. I've called ordered collections of items "arrays" for a very long time, and have never used PHP where they usurped the term to mean "associative array". – Greg Hewgill Jun 29 '09 at 19:54
-1

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?

eduffy
  • 39,140
  • 13
  • 95
  • 92
  • 1
    Instead of using self.__dict__[etc] you'll want to use setattr(self, etc), and I'm sure you meant to say 'list' instead of 'array'. Good use of string formatting though. – tgray Jun 29 '09 at 20:02