0

Let's say I want to create a lot of instances of a class but don't want to write the variable name down for every instance.

What I want:

value1 = class(value1)
value2 = class(value2)
.
.
. 

My idea was:

list = ['One','Two','Three']

for value in list:
    value = class(value)

The result is not what I wanted. Python creates the variable 'value' and overrides it with the values of the list.

I'm sorry to ask such a basic question, but I'm not sure how to handle this.

2
  • 1
    Use a container like a list or a dict, in this case, a list seems appropriate Commented Mar 21, 2019 at 18:09
  • 1
    values = [class(x) for x in list] Commented Mar 21, 2019 at 18:13

2 Answers 2

1

First of all, note that you should not use list as a variable name, as it is reserved as a keyword by Python itself. Then, you could have another list, instanceList lets say, in which you will append every newly created instance of a class:

myList = ['One','Two','Three']
instanceList = []

for value in myList:
    instanceList.append(class(value))
Sign up to request clarification or add additional context in comments.

Comments

1

You can use a list comprehension to build a list of class instances from a list of values:

class A:
    def __init__(self, value):
        self.value = value

values = ['One','Two','Three']
instances = [A(v) for v in values]
>>> print(list(o.value for o in instances))
['One', 'Two', 'Three']

2 Comments

[A(v) for v in values] is a list comprehension - he just uses a generator expression to print the results.
I'm not sure to understand your question/remark, but if you need a generator instead of a list, then you can just replace instances = [...] by instances = (...). Another legitimate option is to use a for-loop as mentioned in this answer.

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.