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

Pijus Virketis virketis@fas.harvard.edu
Mon, 4 Feb 2002 00:39:32 -0500


> > >>> 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:

There are three quite distinct steps happening here:

1. Make a list of data to be used for creating the objects and call it
"names"; use a "for loop" (the bit of code above) to take each entry in the
names and put it into the variable "n".

2. Instantiate a "Person" with a name "n";

3. Store each class instance in the "people" list.

The list.append() syntax belongs to the last step and has nothing to do with
instantiating classes. In other words, the code above could be written more
explicity thus:

for name in names:
    new_person = Person(name)    #instantiate class
    people.append(new_person)    #append it to list

Notice that while I name each Person instance "new_person", I keep
overwritting it, because the people list is the thing that really lets me
keep the instances separate. I no longer need to say Bob = Person("Bob") and
John = Person("John"). I can just access them by calling people[0] and