- 61.5k
- 14
- 134
- 194
ToA list comprehension can be used to fill a list with seperateseparate instances of a class, you can use a for loop in the declaration of the list. The * multiply will link each copy to the same instance.like so:
instancelist = [ MyClass[MyClass() for i in range(29)]
and then access the instances through the index ofThis avoids the problem with multiplying a list of one element with *, which re-uses the same object.
instancelist[5].attr1 = 'whamma'
To fill a list with seperate instances of a class, you can use a for loop in the declaration of the list. The * multiply will link each copy to the same instance.
instancelist = [ MyClass() for i in range(29)]
and then access the instances through the index of the list.
instancelist[5].attr1 = 'whamma'
A list comprehension can be used to fill a list with separate instances of a class, like so:
instancelist = [MyClass() for i in range(29)]
This avoids the problem with multiplying a list of one element with *, which re-uses the same object.
To fill a list with seperate instances of a class, you can use a for loop in the declaration of the list. The * multiply will link each copy to the same instance.
instancelist = [ MyClass() for i in range(29)]
and then access the instances through the index of the list.
instancelist[5].attr1 = 'whamma'