Skip to main content
Stack Overflow
  1. About
  2. For Teams

Return to Answer

use proper terminology; depersonalize language; add reference link; write more clearly; rm noise about how to index into the list (that is a separate question, and presumed already understood)
Source Link
Karl Knechtel
  • 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.

Source Link
Zoomulator
  • 21.3k
  • 7
  • 33
  • 33

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'
Post Made Community Wiki by Community Bot
lang-py

AltStyle によって変換されたページ (->オリジナル) /