How to create multiple class objects with a loop in python?

class, object, python

Solution

This question is asked every day in some variation. The answer is: keep your data out of your variable names, and this is the obligatory blog post.

In this case, why not make a list of objs?

objs = [MyClass() for i in range(10)]
for obj in objs:
    other_object.add(obj)

objs[0].do_sth()

Problem

Suppose you have to create 10 class objects in python, and do something with them, like: ``` obj_1 = MyClass() other_object.add(obj_1) obj_2 = MyClass() other_object.add(obj_2) . . . obj_10 = MyClass() other_object.add(obj_10) ``` How would you do it with a loop, and assign a variable to each object (like `obj_1`), so that the code will be shorter? Each object should be accessible outside the loop ``` obj_1.do_sth() ```

Original source