array of objects
fredrik at effbot.org
Sun Dec 31 05:57:28 EST 2000
Anders Olme wrote:
> How do I create a array of object from my own classes?
> If I have a class like this:
> class test:
> def dosomething(self):
> return 1234
> obj= test()
> obj= [test(),test()]
> The last line works but is there a more elegant way?
Not if you need exactly two elements ;-)
To create a list containing N instances, you can use a
obj = [test() for x in range(N)]
which is short for
obj = 
for x in range(N):
If the test class is "immutable" (that is, if it cannot be modified
in place), you can also use "sequence multiplication":
obj = [test()] * N
this creates a list with N references to the same instance.
More information about the Python-list