[Tutor] Instantiating large numbers of objects? [lists and dictionaries]

Andy W toodles@yifan.net
Mon, 4 Feb 2002 13:49:06 +0800


> > >>> names = ['bart', 'lisa', 'marge', 'homer']
> > >>> people = []
> > >>> for n in names:
> > ...     people.append(Person(n))
> > ...
>
>  Just wondering how this last line works. I've only created instances
> of a class by going:
>
> >>>lisa = Person()
>
>  Apparently when you're adding classes to a list, the syntax is
> different? Do I understand this correctly?

How do you mean?
The initialisation of an instance is the same in and out of lists, and also
the syntax used is the same for adding any type of item to a list.
ie. the_list.append(item)

Danny just skipped the step in which an instance is bound to a name (because
it's unnecessary), and added it straight into the list.
What I mean is, you could either do:

person=Person()
people.append(person)

or the way Danny did it:

people.append(Person())

Alternatively, if you will have your people "hard-coded", you might just
have a predefined list of people:
people=[Person("bart"), Person("lisa"), Person("marge"), Person("homer")]

(BTW, I'm not sure if that "name" argument passed to the Person class was
your idea or not to start with, Britt, but I just used it then to make it
more clear)

>
>  <snip>
>
> > That is, it might be nice to use the person's name to pull them from
> > our
> > list container.  In that case, we can use a more appropriate data
> > structure, the dictionary:
> >
> > ###
> > >>> people_dict = {}
> > >>> for n in names:
> > ...     people_dict[n] = Person(n)
> > ...
> > >>> people_dict['lisa'].sing()
> > tra la la, my name is lisa
> > ###
>
>  Again, the syntax is a little different than what I'm used to. I've
> always never seen a dictionary done like this. Is it a case where the
> syntax is different since its being added to a list?

How have you seen dictionaries used? Like following?
some_dictionary={"predefined_1":"ning","predefined_2":"nang","predefined_3":
"nong"}

Also, it's not being added to a list. The dictionary is being subscripted,
which accesses an existing key, or creates a new one if it doesn't exist.
This is useful (as others pointed out) because it can then be used to access
the Person(s) by "name". I'm not sure if that's helped at all now, because I
couldn't actually think of anything much new to say... oh well.

Andy W.

>
>  Thanks!
>
>  Britt
>
> =====
> "The ocean, she is strange and wondrous, filled with animals that disturb
even a Frenchman."
>
> __________________________________________________
> Do You Yahoo!?
> Great stuff seeking new owners in Yahoo! Auctions!
> http://auctions.yahoo.com
>
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>