array of objects
Daniel Klein
DanielK at aracnet.com
Sun Dec 31 11:14:27 EST 2000
How then is list comprehension different (and/or better) than say:
obj = []
for x in range(N): obj.append(test())
Happy (real) New Millenium,
Daniel Klein
Portland, OR USA
"Fredrik Lundh" <fredrik at effbot.org> wrote in message
news:siE36.2779$Qb7.318673 at newsb.telia.net...
> 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
> list comprehension:
>
> obj = [test() for x in range(N)]
>
> which is short for
>
> obj = []
> for x in range(N):
> obj.append(test())
>
> 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.
>
> </F>
>
>
More information about the Python-list
mailing list