2

I would like to create new variables from a list.

For example:

mylist=[A,B,C]

From which i would like to create the following variables:

self.varA
self.varB
self.varC

How can create these new variables in a loop?

2 Answers 2

6
mylist=['A','B','C']
for name in mylist:
    setattr(self, name, None)

but this is nearly always a bad idea and the values should be in a dict like:

self.v = {}
for name in mylist:
    self.v[name] = None
Sign up to request clarification or add additional context in comments.

1 Comment

+1, and just because you can do something in Python doesn't mean you should
0

Your question ignores the fact that the variables need values ... who is going to supply what values how? Here is a solution to one of the possible clarified questions:

With this approach, the caller of your constructor can use either a dict or keyword args to pass in the names and values.

>>> class X(object):
...     def __init__(self, **kwargs):
...         for k in kwargs:
...             setattr(self, k, kwargs[k])
...

# using a dict

>>> kandv = dict([('foo', 'bar'), ('magic', 42), ('nix', None)])
>>> print X(**kandv).__dict__
{'nix': None, 'foo': 'bar', 'magic': 42}

# using keyword args

>>> print X(foo='bar', magic=42, nix=None).__dict__
{'nix': None, 'foo': 'bar', 'magic': 42}

1 Comment

I actually managed to get it right with setattr and getattr in the following manner: for c in curlist: setattr(self, "penum"+c, 0) … … valuel=getattr(self,(entlistnum[n]+curlist[c])) setattr(self,(entlistnum[n]+curlist[c]),valuel+1) In any case, thank you for your valuable explanation.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.