[Tutor] variable initialization

Danny Yoo dyoo@hkn.eecs.berkeley.edu
Tue, 1 Oct 2002 17:31:59 -0700 (PDT)


On Tue, 1 Oct 2002, Joshua Pollack wrote:

> Hmm... one more question then.
>
> Say I'm wanting to initialize a large number of variables to 0 or even
> as lists.  For instance, if I wanted to initialize 100 different
> variables without having to write out:

If the variables are related in some way --- that is, if they can be
treated as a "collection" or a "group" --- then a Python list may be a
good way to approach this.

Instead of making one hundred variables (which would be tedious!), we can
make one variable with one hundred "slots" or "indices":

###
mylist = []
for i in range(100):
    mylist.append(0)
print mylist[0]
print mylist[42]
print mylist[99]
###

Hmmm.  Since everything's initialized to zero, this is not that exciting.
*grin*

But I hope it makes the use clear: once we have our list, we can pick out
individual elements of it by using indicing '[]'.