[Tutor] Two questions

Erik Price erikprice@mac.com
Sat, 13 Apr 2002 11:20:25 -0400


On Saturday, April 13, 2002, at 10:04  AM, Lloyd Kvam wrote:

> You need to create a (possibly empty) list before you can stick
> something into the list.

I thought that, being a dynamically typed language, you could just 
create list elements on the fly (in the way that henry steigerwaldt did 
in his original script).  I know/have heard that it's good practice to 
declare a variable first, like

site_url = []

but I thought that it was possible to just jump in and start assigning 
directly to elements in a list.  I can't -- even if I declare site_url 
as a list, the following doesn't work:

 >>> site_url=[]
 >>> site_url[0] = 'hi'
Traceback (most recent call last):
   File "<stdin>", line 1, in ?
IndexError: list assignment index out of range

Why is that?  I thought dynamic typing was more flexible than this... ?

> i = 0
> site_url = []	# create an empty list
> site_url[i] = fileobject.readline()
> print "site_url = ", site_url[i]
>
> It is usually simpler to not track the positions when putting
> things into the list.  Something like:
>
> site_url = []
> site_url.append( fileobject.readline())
>
> simply adds the url to the end of the list.  You can NOT add
> things to a tuple.  A tuple can NOT be changed.  If you want your
> URLs to be in a tuple, create the list first.  Then use the
> builtin tuple function.

Then how come I can do:

tuple1 = (1, 2)
tuple2 = (3, 4)
tuple3 = tuple1 + tuple2
(1, 2, 3, 4)

or is that because I'm creating a new tuple?

Erik