Michael
Michael

Reputation: 1

Declaring variables in a list, but defining them in a loop?

Is there any way to declare a bunch of variables in a list, and then define them in a for loop like so?

myList = [a,b,c,d]

for var in myList:
var = 1

So that a, b, c, and d would all end up as 1? Right now if I try and run this code I get an error telling me "a is not defined".

Upvotes: 0

Views: 83

Answers (2)

abarnert
abarnert

Reputation: 365737

This is almost always a very bad idea, but here's how you can do it if you must:

First, you need to put the names of the variables in the list, not the variables themselves. As the error is telling you, a isn't defined yet, so you can't put it into a list. And, even if it were defined, you'd just be putting the value of a into the list, which wouldn't help you. So:

myList = ['a', 'b', 'c', 'd']

Then, you just need to add them to globals (or locals, or builtins, or the class you're currently defining, etc., depending on what namespace you're trying to define them in).

for var in myList:
    globals()[var] = 1

If you want to access the variables dynamically, you're going to need the same kind of tricks to use the variables you just defined. Why bother? Just put them in a dictionary:

myDict = {var: 1 for var in myVars}

Or maybe a custom object, or a namedtuple:

myNames = namedtuple('namespace', myList)(1 for _ in myList)

Then you can access them as:

myDict['a']
myNames.a

Compare that to what you have to do if you're trying to make them variables:

globals()['a']

And if you're just looking for a more concise way to declare them statically, this obviously isn't helping. Compare the three lines of complicated code with the normal version:

a = b = c = d = 1

Really, whenever you have to use globals and friends (or, similarly, setattr and friends), you're forced to step back a level in your head, and start mixing up variable names as strings.

There are occasionally good reasons to do this (more often for setattr than for globals), but they're not that common. Whenever you think you want this, the first step should be to ask yourself (or other people) if there's a better way to solve your actual problem so it isn't needed.

Upvotes: 1

Peter Collingridge
Peter Collingridge

Reputation: 10979

I think it would be better to use a dictionary for what you want.

>>> my_vars = {'a': 1, 'b': 1, 'c': 1, 'd': 1}
>>> print my_var['a']
>>> 1

Or my_vars = dict((x, 1) for x in ['a', 'b', 'c', 'd'])

Upvotes: 2

Related Questions