List of Objects

datamonkey.ryan at gmail.com datamonkey.ryan at gmail.com
Thu Apr 19 23:26:05 EDT 2007


These methods work. I didn't think I could create a list of objects
like that, however, I stand corrected.
Thanks for your quick (and helpful) responses!


On Apr 19, 11:22 pm, Steven D'Aprano
<s... at REMOVEME.cybersource.com.au> wrote:
> On Thu, 19 Apr 2007 19:58:35 -0700, datamonkey.ryan wrote:
> > Howdy, a (possibly) quick question for anyone willing to listen.
> > I have a question regarding lists and Classes; I have a class called
> > "gazelle" with several attributes (color, position, etc.) and I need
> > to create a herd of them. I want to simulate motion of individual
> > gazelles, but I don't want to have to go through and manually update
> > the position for every gazelle (there could be upwards of 50). I was
> > planning to create an array of these gazelle classes, and I was going
> > to iterate through it to adjust the position of each gazelle. That's
> > how I'd do it in C, anyway. However, Python doesn't support pointers
> > and I'm not quite sure how to go about this. Any help you can provide
> > would be greatly appreciated.
>
> First method: create 1000 different gazelles:
>
> list_of_beasties = []
> for i in xrange(1000): # create 1000 beasties
>     args = (i, "foo", "bar") # or whatever
>     list_of_beasties.append(Gazelle(args))
>
> Second method: create 1000 different gazelles by a slightly different
> method:
>
> list_of_beasties = [Gazelle((i, "foo", "bar")) for i in xrange(1000)]
>
> Third method: create 1000 copies of a single gazelle:
>
> list_of_beasties = [Gazelle(args)] * 1000
> # probably not useful...
>
> Forth method: create identical gazelles, then modify them:
>
> list_of_beasties = [Gazelle(defaults) for i in xrange(1000)]
> for i, beastie in enumerate(xrange(1000)):
>     list_of_beasties[i] = modify(beastie)
>
> --
> Steven D'Aprano





More information about the Python-list mailing list