sequence of objects

Neal D. Becker ndbecker2 at verizon.net
Wed Oct 13 13:43:14 EDT 2004


Jeremy Jones wrote:

> Neal D. Becker wrote:
> 
>>What is the recommended way to create a sequence of objects?  Assume the
>>objects have a default constructor:
>>
>>class X:
>>  def __init__(self):
>>    something
>>
>>This doesn't work:
>>a = 64*(X(),)
>>
>>This creates a tuple of 64 copies of a single identical object, not 64
>>instances of X.
>>
>>I could create an empty list, then call append (X()) 64 times, but that's
>>not very eligant (or maybe efficient).  Any suggestions?
>>
>>  
>>
> The answer is, "it depends on what you are trying to do."  Here is _a_
> solution:
> 
> 
> In [5]: class X:
>    ...:     def __init__(self, id):
>    ...:         self.id = id
>    ...:
> 
> In [6]: def gen_64():
>    ...:     for i in range(64):
>    ...:         yield X(i)
>    ...:
> 
> 
> And if you want to iterate through them, you can do something like:
> 
> 
> In [7]: for i in gen_64():
>    ...:     print i, i.id
> 

Sorry, poorly phrased.  I mean a "container of objects", not "sequence of
objects".  For example, a list of 64 X instances.  I did notice that this
can be done with Numeric array also.




More information about the Python-list mailing list